> ## Documentation Index
> Fetch the complete documentation index at: https://developer.upsun.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Workload authorizations

> An authorizations list that grants applications and tasks narrowly-scoped access to the environment API and task operations.

export const DynamicCodeBlock = ({language = 'yaml', filename, icon, lines, wrap, expandable, highlight, focus, children}) => {
  const STORAGE_KEY = 'upsun_versions_cache';
  const COMPOSABLE_STORAGE_KEY = 'upsun_composable_cache';
  const CACHE_TTL = 5 * 60 * 1000;
  const API_URL = 'https://meta.upsun.com/images';
  const COMPOSABLE_API_URL = 'https://meta.upsun.com/composable';
  const DEBUG_PREFIX = '[DynamicCodeBlock cache]';
  const [versionData, setVersionData] = useState(null);
  const [versionError, setVersionError] = useState(false);
  const [composableData, setComposableData] = useState(null);
  const [composableError, setComposableError] = useState(false);
  useEffect(() => {
    const fetchData = async () => {
      let cachedData = null;
      let cachedEtag = null;
      if (typeof localStorage !== 'undefined') {
        try {
          const cached = localStorage.getItem(STORAGE_KEY);
          if (cached) {
            const parsed = JSON.parse(cached);
            cachedData = parsed?.data || null;
            cachedEtag = parsed?.etag || null;
            if (cachedData && Date.now() - parsed.timestamp < CACHE_TTL) {
              return cachedData;
            }
          }
        } catch (err) {
          console.error('Failed to load from cache:', err);
        }
      }
      const requestHeaders = cachedEtag ? {
        'If-None-Match': cachedEtag
      } : {};
      console.debug(`${DEBUG_PREFIX} revalidating`, {
        storageKey: STORAGE_KEY,
        hasCachedData: Boolean(cachedData),
        hasCachedEtag: Boolean(cachedEtag)
      });
      const response = await fetch(API_URL, {
        headers: requestHeaders
      });
      if (response.status === 304 && cachedData) {
        console.debug(`${DEBUG_PREFIX} revalidated (304)`, {
          storageKey: STORAGE_KEY
        });
        if (typeof localStorage !== 'undefined') {
          try {
            const etag = response.headers.get('etag') || cachedEtag;
            localStorage.setItem(STORAGE_KEY, JSON.stringify({
              data: cachedData,
              etag,
              timestamp: Date.now()
            }));
          } catch (err) {
            console.error('Failed to refresh cache metadata:', err);
          }
        }
        return cachedData;
      }
      if (!response.ok) throw new Error(`API request failed: ${response.statusText}`);
      const data = await response.json();
      const etag = response.headers.get('etag');
      console.debug(`${DEBUG_PREFIX} refreshed (200)`, {
        storageKey: STORAGE_KEY,
        etag
      });
      if (typeof localStorage !== 'undefined') {
        try {
          localStorage.setItem(STORAGE_KEY, JSON.stringify({
            data,
            etag,
            timestamp: Date.now()
          }));
        } catch (err) {
          console.error('Failed to cache data:', err);
        }
      }
      return data;
    };
    fetchData().then(data => setVersionData(data)).catch(err => console.error('Failed to fetch version data:', err));
  }, []);
  const findHighestVersion = versionsMap => {
    if (!versionsMap || Object.keys(versionsMap).length === 0) return null;
    const entries = Object.entries(versionsMap);
    const active = entries.filter(([, v]) => v.upsun && v.upsun.status === 'supported' || v.upsun && v.upsun.status === 'deprecated');
    const candidates = active.length > 0 ? active : entries;
    let [highestName] = candidates[0];
    for (let i = 1; i < candidates.length; i++) {
      const [currentName] = candidates[i];
      const cp = currentName.split('.').map(Number);
      const hp = highestName.split('.').map(Number);
      for (let j = 0; j < Math.max(cp.length, hp.length); j++) {
        if ((cp[j] || 0) > (hp[j] || 0)) {
          highestName = currentName;
          break;
        } else if ((cp[j] || 0) < (hp[j] || 0)) {
          break;
        }
      }
    }
    return highestName;
  };
  const getVersion = (lang, requestedVersion = 'latest') => {
    if (lang === 'composable') {
      if (!composableData || !composableData.versions || Object.keys(composableData.versions).length === 0) return null;
      if (requestedVersion && requestedVersion !== 'latest') {
        return (requestedVersion in composableData.versions) ? requestedVersion : null;
      }
      return findHighestVersion(composableData.versions);
    }
    if (!versionData) return null;
    const imageData = versionData[lang];
    if (!imageData || !imageData.versions || Object.keys(imageData.versions).length === 0) {
      return null;
    }
    if (requestedVersion && requestedVersion !== 'latest') {
      return (requestedVersion in imageData.versions) ? requestedVersion : null;
    }
    return findHighestVersion(imageData.versions);
  };
  let code = typeof children === 'string' ? children : String(children || '');
  const codeLines = code.split('\n');
  while (codeLines.length > 0 && codeLines[0].trim() === '') codeLines.shift();
  while (codeLines.length > 0 && codeLines[codeLines.length - 1].trim() === '') codeLines.pop();
  if (codeLines.length > 0) {
    const indents = codeLines.filter(line => line.trim().length > 0).map(line => line.match(/^[ \t]*/)[0].length);
    const minIndent = Math.min(...indents);
    code = codeLines.map(line => line.slice(minIndent)).join('\n');
  }
  code = code.replace(/\{\{version:(.*?)\}\}/g, (match, params) => {
    const parts = params.split(':');
    const lang = parts[0];
    const ver = parts[1] || 'latest';
    const isComposable = lang === 'composable';
    const hasError = isComposable ? composableError : versionError;
    const dataReady = isComposable ? composableData !== null : versionData !== null;
    if (hasError) return '(unavailable)';
    if (dataReady) {
      const resolvedVersion = getVersion(lang, ver);
      return resolvedVersion || match;
    }
    return '...';
  });
  const codeBlockProps = {
    language,
    ...filename && ({
      filename
    }),
    ...icon && ({
      icon
    }),
    ...lines !== undefined && ({
      lines
    }),
    ...wrap !== undefined && ({
      wrap
    }),
    ...expandable !== undefined && ({
      expandable
    }),
    ...highlight && ({
      highlight
    }),
    ...focus && ({
      focus
    })
  };
  return <CodeBlock {...codeBlockProps}>{code}</CodeBlock>;
};

Upsun runs several types of workloads — applications, workers, crons, and tasks. The `authorizations` key enables a workload to call the
Upsun API at runtime using short-lived, narrowly-scoped tokens, with no long-lived credentials required.
This key can be declared on both applications and tasks, but serves a different purpose depending on where it's declared:

* On an **application**: grants permission to trigger tasks and call the environment API.
* On a [**task**](/docs/configure-apps/tasks): grants the task permission to call the environment API from inside its container. A task can also trigger another task.

  <Note>
    Tasks are in **prerelease**. To request this feature on your project, [open this prepopulated support ticket](https://console.upsun.com/-/users/-/tickets/open?isGeneral=true\&category=feature_request_cat\&priority=normal\&subject=Enable%20task%20containers%20\(prerelease\)%20on%20my%20project\&description=Hello%2C%20I%27d%20like%20to%20enable%20task%20containers%20on%20my%20project.%0A%0AProject%20ID%3A%20%3CPROJECT_ID%3E) and add your project ID before submitting.
  </Note>
* On a [**worker**](/docs/configure-apps/image-properties/workers): inherits the application's `authorizations` by default, or overrides them — the same as other application properties
  that can be set in a web or worker instance (such as `relationships`, `mounts`; for a complete list, refer to the **Set in instance** column of the
  **Primary applicaton properties** table in the [single-runtime](/docs/configure-apps/app-reference/single-runtime-image#primary-application-properties)
  and [composable image](/docs/configure-apps/app-reference/composable-image#primary-application-properties) topics).
* On a **cron**: crons run inside the application container and inherit its `authorizations` automatically. You cannot grant different authorizations to individual crons.

The `authorizations` key grants an application or task permission to make specific calls to the Upsun API from inside its container.
Each authorization defines a `type` and an `action`, and optionally a `resource` to scope the permission.

No user API token or long-lived credential is required.
The platform injects a short-lived bearer token at runtime, scoped to the permissions declared here.

## How it works

Instead of storing a long-lived API token in your environment, every application and task container has a local auth proxy running at `http://localhost:8200`.
The proxy issues short-lived tokens scoped to the permissions you declared — so there are no credentials to rotate, and a token issued in one environment cannot act on another.

When your code needs to call the Upsun API:

1. Your app sends a token request to `http://localhost:8200/oauth2/token`.
2. The proxy returns a bearer token scoped to those declared permissions.
3. Your app uses that token to call the Upsun API.

## Parameters

| Parameter  | Values            | Description                                                                                             |
| :--------- | :---------------- | :------------------------------------------------------------------------------------------------------ |
| `type`     | `task`, `env`     | The type of resource to access: `task` — a task defined in your project. `env` — the environment API.   |
| `resource` | Task name         | The name of the task. Required when `type` is `task`.                                                   |
| `action`   | `operate`, `view` | `operate` allows triggering and managing a task. `view` grants read-only access to the environment API. |

### Valid combinations

| `type` | `action`  | `resource` | What it grants                          |
| :----- | :-------- | :--------- | :-------------------------------------- |
| `task` | `operate` | Task name  | Trigger and manage the named task       |
| `env`  | `view`    | —          | Read-only access to the environment API |

## Examples

Allow an application to trigger a task and read the environment API:

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      applications:
        myapp:
          authorizations:
            - type: task
              resource: myagent
              action: operate
            - type: env
              action: view`
  }
</DynamicCodeBlock>

Allow a task to read the environment API:

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      tasks:
        myagent:
          authorizations:
            - type: env
              action: view`
  }
</DynamicCodeBlock>
