Skip to content

Access and scopes

A scope names one kind of permission, such as users:read or groups:delete. The SDK uses scopes in three distinct places. Only NOMAD makes the final decision about whether a request is allowed.

Setting Where you set it What it does
enforced_scopes NomadClient A local limit. The client refuses operations outside it before signing in or sending a request.
requested_scopes PasswordCredential, BrowserCredential Advanced. Scope names sent during sign-in. An OIDC provider processes browser scopes; stock NOMAD 2.x ignores the password form field. Neither setting is a local policy.
granted_scopes Read-only on every credential The scopes the token is known to carry, or None when the SDK cannot know them.

How a request is checked

flowchart TD
    signin["Sign-in<br/>credential sends requested_scopes<br/>(identity service decides)"] -.-> token[(Access token)]
    call["client.identity.groups.delete(...)"] --> required["Operation declares<br/>required_scopes"]
    required --> enforced{"Inside the client's<br/>enforced_scopes?"}
    enforced -- no --> notallowed["ScopeNotAllowedError<br/>nothing sent"]
    enforced -- "yes or not set" --> granted{"Inside the credential's<br/>granted_scopes?"}
    granted -- no --> notgranted["ScopeNotGrantedError<br/>nothing sent"]
    granted -- "yes or unknown" --> send["Request sent with the token"]
    token --> send
    send --> nomad{"NOMAD checks the token<br/>and the resource"}
    nomad -- refused --> denied["AuthorizationError (403)"]
    nomad -- allowed --> ok["Result"]

Compare the three settings

enforced_scopes requested_scopes granted_scopes
Set on NomadClient(enforced_scopes=...) PasswordCredential(...), BrowserCredential(...) Read-only property of the credential
Who decides You, locally You ask; the identity service decides NOMAD, when it issued an SDK-created PAT
Sent over the network Never Yes, as the OAuth scope value at sign-in No
Restricts the token No Only if the deployment honours it Describes the token
Checked before a request Yes, raises ScopeNotAllowedError No Yes when known, raises ScopeNotGrantedError
Effect on NOMAD Central today Reliable Browser values are OIDC client scopes but do not narrow NOMAD API permissions; the password value is ignored Known only for PATs from from_issued
Typical use Everyday local guard Advanced, when an identity administrator requires an OIDC client scope, audience, claim, or refresh-token scope Automatic with SDK-created PATs
Values Scope members Strings or Scope members Strings

Browser and password tokens carry your full user scopes

NOMAD gives a Keycloak access token the full set of user scopes, and the token cannot be narrowed at sign-in. A scoped personal access token is the only token NOMAD restricts per token. An Oasis administrator can still limit the effective scopes for whole groups of users (see server-side scope settings). Use enforced_scopes to restrict what your code attempts with a broad token.

Effective scopes on the server

NOMAD decides which scopes apply to each request before checking the endpoint:

Request Effective scopes
No token, authentication not required The deployment's unauthenticated_user_scopes
Valid token, user authorized (or no authorized_users list) The token's scopes: full user scopes for Keycloak, the selected scopes for a PAT
Valid token, user not in authorized_users Refused (403) if reject_unauthorized_users, otherwise unauthorized_user_scopes

NOMAD then requires every scope the endpoint declares. No scope implies another, and wildcards such as *:read are allowed only in deployment configuration, never in tokens. Access to the specific upload, group, or other resource is checked as well. NOMAD authorization model

Which one should I set?

  • Least privilege that NOMAD enforces: create a PAT with only the scopes the job needs. Add enforced_scopes if you also want local errors before any request.
  • Browser or password sign-in on Central or a stock Oasis: set enforced_scopes. It is the only restriction that applies to these tokens.
  • Real per-job least privilege with browser or password sign-in: sign in, create a short-lived PAT with only the job's scopes, and run the job with that PAT.
  • Advanced identity configuration: use requested_scopes only when the identity administrator specifies the exact OIDC client-scope names. See Advanced: request scopes at sign-in.

client.enforced_scopes is a read-only property. Call client.identity.get_operation_info("me") to see what an operation requires. Scope.USERS_READ is a member of the Scope enum.

With NOMAD_PAT set, compare your local policy with the scopes required by me() before looking up the account.

import os

from nomad_python_api import NomadClient, Scope
from nomad_python_api.identity import BearerTokenCredential

credential = BearerTokenCredential(os.environ["NOMAD_PAT"])
with NomadClient(credential=credential, enforced_scopes={Scope.USERS_READ}) as client:
    # Compare the client's policy with the operation's requirements.
    info = client.identity.get_operation_info("me")
    print("Enforced:", sorted(scope.value for scope in client.enforced_scopes or ()))
    print("Required:", sorted(scope.value for scope in info.required_scopes))

    account = client.identity.me()
    print("Account returned:", bool(account.user_id))
    print("Username available:", account.username is not None)

Enforced and Required both show users:read. A successful lookup prints Account returned: True. Username available depends on the account returned by NOMAD.

Restrict a client with enforced_scopes

enforced_scopes is a guard against mistakes, such as rerunning the wrong notebook cell or a bug in a helper. It is checked before the credential signs in, so a blocked call never sends a request. The client keeps an immutable copy of the set. Leave it unset (None) for no local limit.

Keep a notebook read-only

Prerequisites: a NOMAD Central account and a local browser.

The browser token could delete groups, but this client may only read.

from nomad_python_api import NomadClient, Scope
from nomad_python_api.exceptions import ScopeNotAllowedError
from nomad_python_api.identity import BrowserCredential

# A browser token carries all of your account's permissions.
credential = BrowserCredential(
    issuer="https://nomad-lab.eu/fairdi/keycloak/auth/realms/fairdi_nomad_prod",
    client_id="nomad_public",
    discover=True,
)

# This notebook may only read, whatever the token would allow.
with NomadClient(
    credential=credential,
    enforced_scopes={Scope.USERS_READ, Scope.GROUPS_READ},
) as client:
    account = client.identity.me()
    print("Signed in as:", account.username)
    try:
        client.identity.groups.delete("example-group-id")
    except ScopeNotAllowedError as error:
        missing = ", ".join(sorted(scope.value for scope in error.missing_scopes))
        print(f"Blocked locally: {error.operation} needs {missing}")

Expected output (the username is yours):

Signed in as: demo
Blocked locally: identity.groups.delete needs groups:delete

No delete request reaches NOMAD.

Give each worker its own policy

Prerequisites: NOMAD_PAT set to a PAT with users:read.

Several clients can share one credential with different limits. Each client checks only its own enforced_scopes.

import os

from nomad_python_api import NomadClient, Scope
from nomad_python_api.identity import BearerTokenCredential

# One credential, two clients with different local policies.
credential = BearerTokenCredential(os.environ["NOMAD_PAT"])
reader = NomadClient(credential=credential, enforced_scopes={Scope.USERS_READ})
maintainer = NomadClient(
    credential=credential,
    enforced_scopes={Scope.USERS_READ, Scope.GROUPS_READ, Scope.GROUPS_WRITE},
)
with reader, maintainer:
    update = maintainer.identity.get_operation_info("groups.update")
    for name, client in (("reader", reader), ("maintainer", maintainer)):
        allowed = update.required_scopes <= (client.enforced_scopes or set())
        print(f"{name} may update groups: {allowed}")
    print("Reader account:", reader.identity.me().username)

Expected output:

reader may update groups: False
maintainer may update groups: True
Reader account: demo

Hand a restricted client to other code

Prerequisites: NOMAD_PAT set to a PAT with users:read.

Pass a read-only client to a helper or plugin. A write inside the helper fails locally, whatever the token allows.

import os

from nomad_python_api import NomadClient, Scope
from nomad_python_api.exceptions import ScopeNotAllowedError
from nomad_python_api.identity import BearerTokenCredential

def summarize_account(client: NomadClient) -> str:
    """A helper that should only ever read."""
    try:
        client.identity.groups.delete("example-group-id")  # A bug in the helper
    except ScopeNotAllowedError:
        pass
    return client.identity.me().username

credential = BearerTokenCredential(os.environ["NOMAD_PAT"])
# Hand the helper a client that can only read your account.
with NomadClient(credential=credential, enforced_scopes={Scope.USERS_READ}) as read_only:
    print("Summary:", summarize_account(read_only))

Expected output: Summary: demo.

A guard, not a sandbox

enforced_scopes limits what one client attempts. Code that holds the credential can still create another client or send raw HTTP. Give untrusted code a narrowly scoped PAT instead.

Know what a PAT was granted

A credential made with BearerTokenCredential.from_issued records the scopes NOMAD issued to the PAT. The client then refuses operations that need other scopes before sending a request, with ScopeNotGrantedError.

Prerequisites: NOMAD_KEYCLOAK_ACCESS_TOKEN set to a Keycloak access token with PAT management permissions (see PATs).

import os

from nomad_python_api import NomadClient, Scope
from nomad_python_api.exceptions import ScopeNotGrantedError
from nomad_python_api.identity import BearerTokenCredential, PatCreateOptions

signed_in = BearerTokenCredential(os.environ["NOMAD_KEYCLOAK_ACCESS_TOKEN"])
with NomadClient(credential=signed_in) as client:
    issued = client.identity.pats.create(
        PatCreateOptions(name="Account check", scopes=[Scope.USERS_READ], expires_in_days=1)
    )

# The SDK knows exactly what NOMAD granted to this PAT.
job_credential = BearerTokenCredential.from_issued(issued)
print("Granted:", sorted(job_credential.granted_scopes or ()))

with NomadClient(credential=job_credential) as job:
    print("Account:", job.identity.me().username)
    try:
        job.identity.groups.delete("example-group-id")
    except ScopeNotGrantedError as error:
        print("Not sent:", error)

Expected output:

Granted: ['users:read']
Account: demo
Not sent: identity.groups.delete requires scopes the credential's token was not granted: groups:delete.

ScopeNotGrantedError and ScopeNotAllowedError are separate NomadError subclasses. Catch them separately when recovery differs: the former needs a credential with broader grants, while the latter needs a different client policy.

A token from elsewhere

The SDK does not decode tokens. For a pasted PAT or a Keycloak token, granted_scopes is None and NOMAD decides.

Prerequisites: NOMAD_PAT set to a PAT without groups:delete.

import os

from nomad_python_api import NomadClient
from nomad_python_api.exceptions import AuthorizationError
from nomad_python_api.identity import BearerTokenCredential

# A pasted token: the SDK cannot know its scopes, so NOMAD decides.
credential = BearerTokenCredential(os.environ["NOMAD_PAT"])
print("Granted:", "unknown" if credential.granted_scopes is None else credential.granted_scopes)
with NomadClient(credential=credential) as client:
    try:
        client.identity.groups.delete("example-group-id")
    except AuthorizationError:
        print("NOMAD refused the request (HTTP 403).")

Expected output:

Granted: unknown
NOMAD refused the request (HTTP 403).

Here the request reaches NOMAD, which refuses it.

Advanced: request scopes at sign-in

An identity request, not a NOMAD permission boundary

requested_scopes gives no local protection and does not narrow standard NOMAD API permissions. Use a scoped PAT for server-enforced per-token least privilege and enforced_scopes for a local operation limit.

BrowserCredential sends these values to Keycloak or another OIDC provider. The provider processes registered client scopes and may use them to add claims or audiences, or to issue a refresh token. Unsupported values may make sign-in fail. A Scope enum member is only converted to its string value; it has no special OIDC meaning unless the provider registered the same name.

PasswordCredential sends the values to NOMAD's /auth/token form. Stock NOMAD 2.x accepts but ignores that field. Leave the option unset unless the deployment's identity administrator gives you exact values.

How requested_scopes is sent, with an example

PasswordCredential sends the names as the scope form field of POST /auth/token. BrowserCredential adds them after openid in the authorization request. Names are sorted and deduplicated. When unset, the password form has no scope field and the browser sends only openid. The SDK accepts at most 64 ASCII names, each at most 256 characters, with a maximum joined value of 2,048 characters. Names cannot contain whitespace, quotes, or backslashes.

Prerequisites: NOMAD_PASSWORD set, and a deployment with password login.

import os

from nomad_python_api import NomadClient, Scope
from nomad_python_api.identity import PasswordCredential

credential = PasswordCredential(
    username="user1",
    password=os.environ["NOMAD_PASSWORD"],
    # Asked for at sign-in. Standard NOMAD ignores it.
    requested_scopes={"users:read"},
)
# The reliable restriction is the client's enforced policy.
with NomadClient(credential=credential, enforced_scopes={Scope.USERS_READ}) as client:
    print("Requested:", credential.requested_scopes)
    print("Account:", client.identity.me().username)

Expected output:

Requested: ('users:read',)
Account: demo

On standard NOMAD the token still carries full user scopes. Only enforced_scopes limits this client.

Troubleshoot a request

Error Raised by Request sent? What to change
ScopeNotAllowedError The client's enforced_scopes No Add the operation's scopes to enforced_scopes, or use a different client.
ScopeNotGrantedError The credential's known granted_scopes No Create a PAT with the missing scopes.
AuthorizationError (403) NOMAD Yes Use a token with the scope, and check your access to the resource. On an Oasis, your account may be outside authorized_users and limited to unauthorized_user_scopes.
ClientAuthenticationError (401) NOMAD Yes Check that the token is valid, unexpired, and issued for this deployment's API.

Set NOMAD_PAT and run this example to check how account lookups report authentication and permission errors.

import os

from nomad_python_api import NomadClient, Scope
from nomad_python_api.exceptions import (
    AuthorizationError,
    ClientAuthenticationError,
    ScopeNotAllowedError,
)
from nomad_python_api.identity import BearerTokenCredential

credential = BearerTokenCredential(os.environ["NOMAD_PAT"])
with NomadClient(credential=credential, enforced_scopes={Scope.USERS_READ}) as client:
    # Report actionable errors without printing the token.
    try:
        account = client.identity.me()
    except ScopeNotAllowedError as error:
        missing = ", ".join(sorted(scope.value for scope in error.missing_scopes))
        print(f"This client blocks scopes required by {error.operation}: {missing}")
    except ClientAuthenticationError:
        print("Check the token value, expiration, and issuing deployment.")
    except AuthorizationError:
        print("Check the token's NOMAD scopes and resource access.")

See exceptions for sign-in errors and API responses.