cs-image-system-okta-opa-plugin
The identity plugin for Okta. It registers the group builders and user
builders that turn the system's groups: and users: collections into
standalone terraform roots: OPA (Okta Privileged Access, provider
okta/oktapam) groups, resource groups, login projects, security policies
and enrollment tokens for groups; okta/okta user resources or lookups for
users. It also supplies the pieces other lifecycles need from an identity
type: the packages a base image bakes for identity_types: [okta], the
activation an instance image bakes for its owning group, the launch
parameters, a read-only gid shim that answers cs-image-system identity export-gids from the OPA Attributes API, the OPA server registry the
instance lifecycle reads and retires, and the CI login policy the identity
lifecycle keeps beside each group's user policy through the OPA API.
Installing
An operator installs the plugin through the system's own extra, beside the extras of the tree's runtimes:
uv tool install 'cs-image-system[okta]'
The plugin is released from its own repository,
infrastructurebuilder/cs-image-system-okta,
from 0.2.0 on (its 0.1.x came out of cs-image-system-3); the okta extra
names it by a range, so a release of the system and a release of the plugin
need not come together. Installing a release, and choosing extras, is in the
system's operations guide.
What it registers
Entry point (pyproject.toml):
[project.entry-points."cs_image_system.plugins.group"]
okta_opa_plugin = "cs_image_system.okta_opa_plugin.main:initialize"
initialize() (main.py)
returns an OktaTypes metadata object (metadata version 1, Python
3.13). Every class is registered under one service key, okta-tf; each
class's own csis_name() supplies the type: value a YAML entry uses.
| YAML collection | type: |
Model class | Builder class | Classification (VCT) |
|---|---|---|---|---|
group_builders: |
okta-tf |
OktaTfGroupBuilderModel |
OktaTfGroupBuilder |
GROUP_BUILDER_MODEL / GROUP_BUILDER |
group_builders: |
okta-tf-ro |
OktaTfGroupRoBuilderModel |
OktaTfGroupRoBuilder |
GROUP_BUILDER_MODEL / GROUP_BUILDER |
user_builders: |
okta-tf |
OktaTfUserBuilderModel |
OktaTfUserBuilder |
USER_BUILDER_MODEL / USER_BUILDER |
user_builders: |
okta-tf-ro |
OktaTfUserRoBuilderModel |
OktaTfUserRoBuilder |
USER_BUILDER_MODEL / USER_BUILDER |
The same two type: keys serve both collections; the collection a builder
sits in decides whether it is a group builder or a user builder. There are
no aliases for these keys. A groups: or users: item selects a builder by
the builder's name (or one of the builder's aliases:), or by default
(the builder with is_default: true).
Two further registrations come with the group builder:
- The identity type token is
okta(OktaTfGroupBuilder.identity_type()). A base image declaresidentity_types: [okta]to receive this plugin's prerequisites. OktaTfGroupBuilder.export_gidsis the gid shim behindcs-image-system identity export-gids.- The
users:item model:OktaUser(okta_user.py), the core'sUserplus the optionalokta_userprofile fields, injected underUSER_MODELas the default item model, so everyusers:item in a tree loads into it while this plugin is installed (and a tree that writes a profile field needs this plugin to load at all).
A second entry point mounts this plugin's commands on the console script
(the contract's cs_image_system.commands group; see "Commands" below):
[project.entry-points."cs_image_system.commands"]
okta_opa_plugin = "cs_image_system.okta_opa_plugin.cli:command_mounts"
Models
All four builder models mix
OktaTfWorkspaceModelMixin
into a base builder model. The mixin carries every field that describes the
terraform workspace (org, team, credentials, providers, state backend); the
base model carries the builder identity and, for users, the templates.
OktaTfWorkspaceModelMixin
Defined in
okta_tf_workspace.py.
Not a model on its own; every OktaTf*BuilderModel below inherits these
fields. The full table is
CONFIGURATION 9.1;
the plugin's own Configuration reference
below repeats it with types and defaults. What each field does here:
org(required): the Okta org name. Fillsapi_hostand theoktaprovider'sorg_name.team(required): the OPA team name. Names theTF_VAR_<team>_key/TF_VAR_<team>_secretvariables (non-alphanumerics become_) and theoktapam_teamprovider argument.key,secret: the OPA API pair. Left atdefault, each resolves at finalize tovar.<team>_key/var.<team>_secret. Either may beENC[age:...].api_host: optional. The OPA API host; also the host the gid shim, the state query and every other OPA API call use. Left unset (or atdefault), it becomeshttps://<org>.pam.okta.com.okta_base_url: theokta/oktaprovider'sbase_url(oktapreview.comfor preview orgs).default_user_status:okta_user.statusfor enabled managed users. Not checked against theokta_userstatus set; the provider refuses an unknown one at plan.required_providers: the providers this root declares, entries withname,source,versionand optionalconfig:. A group root namesoktapam; a user root or read-only group root namesokta.state_configuration: the name of astate_backends:entry (foreign key toSTATE_BACKEND_MODEL).defaultpicks the default backend; the identity roots have no runtime, so there is no runtime rung in between.
Behaviour attached to these fields:
provider_variables(): theoktapamprovider gets two sensitive string variables,<team>_keyand<team>_secret; theoktaprovider gets none.transform_provider(): foroktapamthe provider block is built fromkey,secret,api_hostandteam(a declared-encrypted value is emitted by reference to its ciphertext, never quoted into HCL). Foroktathe YAMLconfig:of the provider entry is used as-is, withorg_nameandbase_urlfilled in only when absent; credentials are never written, the provider readsOKTA_API_*from the environment. Any other provider name is passed through with a warning.finalize():api_hostdefaults fromorg. Whenoktapamis among the providers,keyandsecretleft atdefaultmust be backed byTF_VAR_<team>_key/TF_VAR_<team>_secretin the environment, otherwise finalize raises aValueErrornaming the missing variable (a real raise, not anassert, so it still fires when Python runs with-O). Whenoktais among the providers and none ofOKTA_API_PRIVATE_KEY,OKTA_API_TOKEN,OKTA_ACCESS_TOKENis set, finalize only warns; the builder then skipsplanat generation time. The warning points at this README's Prerequisites and integration section.
OktaGroupBuilderModel
Defined in okta_tf_models.py.
Extends
GroupBuilderModel,
which itself adds nothing to
BuilderModel
(name, type, description, aliases, executable, is_default,
config, gitignore, tags). The full table is
CONFIGURATION 9.2. The
keys this plugin adds:
gateway_selector: thegateway_selectorof every group's login project.account_discovery: theaccount_discoveryof every group's login project.workload_connection: the name of the team's OPA workload connection, made by hand once (CI_SETUP.md, section 3.5). Read only together withworkload_role.workload_role: the name of the team's one workload role. With both names set, the builder keeps one CI login policy per managed group (<group>_v1_security_policy_ci) through the OPA API and reports it in the state query.
effective_gateway_selector(config) returns gateway_selector when set,
otherwise the okta_gateway_selector value of the config: map it is
given (the group builder passes its run's, ctx.config), otherwise None
(the module call then omits the argument). It was a property that fetched
the process's current context; a model holds no context, so the caller
hands the map in.
OktaTfGroupBuilderModel (okta-tf)
Defined in
okta_opa_tf_group_models.py.
OktaTfWorkspaceModelMixin + OktaGroupBuilderModel, plus posix
(required) and posix_ssh_keys. The managed group root: it expects
oktapam in required_providers.
OktaTfGroupRoBuilderModel (okta-tf-ro)
Same file; extends OktaTfGroupBuilderModel and adds no fields. The
read-only group root: it expects okta in required_providers, because the
oktapam provider has no group data source.
OktaUserBuilderModel and OktaTfUserBuilderModel (okta-tf)
OktaUserBuilderModel
(okta_tf_models.py)
extends
UserBuilderModel
and adds no fields. OktaTfUserBuilderModel
(okta_opa_tf_user_models.py)
mixes in the workspace fields. The full table is
CONFIGURATION 9.3. What
this plugin does with the base fields:
default_user_email_templaterenders a user'semailwhen the item leaves it atdefault. The email is the value theokta_userlookup searches for (profile.login).default_user_description_templaterenders a user'sdescription; not emitted into HCL.email_domainis the organisation half of a derived address; folded into the template where it says{{ builder.email_domain }}. Declared encrypted, one marker serves every derived address.email_as_username: when true,user.namemust equaluser.email(case-insensitive) or the run aborts; a blank name is set from the email.
OktaTfUserRoBuilderModel (okta-tf-ro)
Same file; extends OktaTfUserBuilderModel, adds no fields. Its builder
defaults every user to lookup-only and refuses managed: true.
Base fields this plugin overrides or constrains
BuilderModel.executablemust name anexecutables:entry whose binary istofu/terraform(the fixture usesopen-tofu-1); every emitted command runs it.BuilderModel.parametersis refused at load (a base-model rule).- The
typeclass attribute on each model is documentation only; the registry keys oncsis_name().
How the group and user items are read
The group items are the base
Group model; the
user items are this plugin's OktaUser
(okta_user.py), the base
User with the Okta
profile fields added (the base carries none of them).
Group fields consumed: name, members, admins, is_root (the root
group's admins are merged into every other group's admins),
include_root_group_in_admins (opts a group out of that merge),
unmanaged (the module call is replaced by a comment and the module is
removed from state by the runner's pre-plan step, never destroyed), attributes (validated against
unix_gid: int, unix_group_name: str, windows_group_name: str; an int
below 1024 is refused). Not consumed: gid (never emitted; the gid policy
is creation-only, OPA assigns it and the root publishes it by reference),
description, tags, config, in_both (the base model applies it
before the builder sees the sets).
User fields consumed: name, first_name, last_name, email,
is_enabled (false maps to status SUSPENDED), managed (per-item
override of the builder's default), attributes (validated against
unix_uid: int, unix_gid: int, unix_user_name: str,
windows_user_name: str), the base's middle_name, and every optional
okta_user profile argument OktaUser carries (mobile_phone, title,
department, manager, ...) when it is set. Not emitted: public_keys,
is_service_account, description.
Terraform emitters
okta_tf_models.py
also holds the TerraformGenerator classes the builders render through
hashicorp-utils:
| Class | Emits |
|---|---|
OktaTFUser |
resource "okta_user" "<label>" (first/last name, login, email, status, optional profile arguments) and data "okta_user" "<label>" with a search { name = "profile.login" ... } block, skip_roles/skip_groups true, and depends_on the resource when the user is managed. |
OktaTFGroupLookup |
data "okta_group" "<label>" by name; no resource. The okta provider's name search is prefix-based, so exact group names are the contract. |
OktaTFGroup, OktaTFUserToGroup, OktaTFResourceGroup, OktaTFSecurityPolicyV1 |
Single-resource emitters for oktapam_group, oktapam_user_group_attachment, oktapam_resource_group + oktapam_resource_group_project, and oktapam_security_policy. The group builder emits a module call instead of these; they are kept, tested, and usable by other code. |
<label> is the item name with every non-alphanumeric character replaced
by _ (avery.alpha becomes avery_alpha).
The builders
All four own a terraform root through
TerraformRootMixin.
Paths below are relative to the run's generation directory
(generated/identity/ when the identity lifecycle runs). <ws> is the
builder's name.
OktaTfGroupBuilder (okta-tf)
okta_opa_tf_group_builder.py.
Extends
GroupBuilderBase.
Every lifecycle hook keys on the group-generation phase and is silent in
every other phase.
generate_items_beforewrites the workspace scaffolding:<ws>/group-generation/<ws>-group-generation.tf: a header comment; theterraform {}block withrequired_providersfrom the model plusexternal = { source = "hashicorp/external" }(the gid shim's provider), and abackend "<type>" {}stanza naming the bound backend's type (localin the fixture,s3in the live tree) whenconfig.use_state_backendsis true; oneproviderblock per provider, each aliased with the workspace name; adata "external" "sensitive"block pluslocals { sensitive = ... }only when a declared-encrypted credential was registered.<ws>/group-generation/<ws>-group-generation-<ws>-vars.tf: the two sensitivevariableblocks for the OPA key and secret.<ws>/group-generation/<ws>-group-generation.tfbackend.hcl: the backend partial configuration the bound backend renders (pathforlocal;bucket,key,region,encrypt,use_lockfile,profilefors3); absent when backends are off.
get_commands_to_run_before: nothing.generate_items_duringwrites, per attached group,<ws>-group-generation-group-<group>.tfholding onemodule "group_<label>"call (or a one-line comment when the group isunmanaged: true), and<ws>-group-generation-outputs.tfholding the root's outputs.get_commands_to_run_during: nothing.generate_items_after: nothing.get_commands_to_run_afterreturns two lists:- Generation-time commands (run in-process, a read):
tofu fmt,tofu init(-backend=falseon a dry run;-reconfigure -backend-config=<file>on a real run),tofu validate, and on a real run only,cs-image-system materialize .followed bytofu initandtofu plan -refresh=falsein the private mirror (_private/identity/<ws>/group-generationunder the configuration root), because the committed emission carries ciphertext and the plan reads plaintext. The plan is a preview:-refresh=falsekeeps the provider from refreshing an attachment whose membership is gone (it errors instead of planning the destroy). - Deferred commands (written to
run-identity.sh, each run inside the private mirror of the root):rm -f tfplan;tofu init -input=false -reconfigure [-backend-config=...];cs-image-system prune-attachments --builder <ws> --tofu <binary> --run <run>(below: the one step in which anything leaves state before the plan);tofu plan -input=false -out=tfplan;cs-image-system gate-plan --planfile tfplan --tofu <binary>; and, only whenconfig.apply_identityallows this root,cs-image-system apply-check --lifecycle identity --root <ws>followed bytofu apply -input=false tfplan. When any group or user declaresattributes:, one more deferred command follows:cs-image-system --root-dir <root> --no-dry-run identity-attributes --probe --dry-run-apply(with--root-dir, because the step loads the configuration and the root's mirror has nocfg/).
- Generation-time commands (run in-process, a read):
pre_finalize_phase/post_finalize_phase: not overridden.
The module call
(_group_module_call)
targets tfmodules/okta_opa_module:
| Module input | Value |
|---|---|
source |
okta_opa_module under config.module_source_base, made relative to the root directory. |
providers |
{ oktapam = oktapam.<ws> } (every bound provider except external). |
group_id |
The group label. The module derives <label>_user and <label>_admin groups, <label>_rg resource group, <label>_rg_login project, one server enrollment token, and the _user/_admin security policies selecting servers labelled system.os_type=linux and sftd.tx.group=<label>. |
members |
The group's members, sorted. |
admins |
The group's admins plus the root group's admins (unless include_root_group_in_admins: false), sorted. |
delegated_admin_group_ids |
Always []; the module then delegates the resource group to the group's own admin group. The root group's admin group is never a delegated admin of another resource group; its admins reach other groups as usernames in admins. |
account_discovery |
The model's account_discovery. |
gateway_selector |
effective_gateway_selector(ctx.config), omitted when None. |
The outputs file declares data "external" "group_gids" (program
cs-image-system identity export-gids, query identity_type, org,
team, api_host, groups) and three outputs: group_gids (group name
to numeric gid), groups (per group: user_group_id, admin_group_id,
resource_group_id, user_group_name) and the sensitive
group_enrollment_tokens. With no managed group the file holds only an
empty group_gids output. Consumers read them through
data.terraform_remote_state.<ws>.outputs;
enrollment_token_reference(group) returns exactly that expression for
the instance lifecycle.
Hooks other lifecycles call on this builder:
| Hook | What it returns |
|---|---|
identity_type() |
okta. |
gid_policy() |
creation-only. |
base_image_prerequisites(os_family) |
Shell lines that install scaleft-server-tools from the OktaPAM repository, then systemctl disable --now sftd and remove /var/lib/sftd/enrollment.token. The repository recipe is this plugin's, chosen by the OS type's package_format(): a deb recipe (the signing key dearmored into a keyring, a sources list; curl and gnupg installed first when absent) or an rpm recipe (rpm --import, a repo file). The install and refresh lines are the OS type's own hooks (package_install_command, package_update_command), never written here; a format OktaPAM publishes nothing for (alpine) is refused with a ValueError naming it. |
verify_commands(os_family) |
Assertions that sftd exists, is not enabled, and has no enrollment token. |
activation_commands(image, group) |
Writes Labels:\n tx.group: <group> to /etc/sft/sftd.yaml and enables sftd. |
activation_verify_commands(image, group) |
Asserts the label is present and sftd is enabled; with a posix: delegate, also that the delegate's login hook stands at the contract's LOGIN_HOOK path (cs_image_system.contract.group, the one declaration both plugins read) and is wired into /etc/pam.d/sshd. |
launch_parameters(group) |
{"enrollment": "sftd-token", "server_label": "sftd.tx.group=<group>"}. |
export_gids(query, groups) |
{group: gid} read from OPA (<group>_user's unix_gid attribute, then the bare name; a group without one is absent, never invented). Credentials come from TF_VAR_<team>_key/_secret or OKTAPAM_KEY/OKTAPAM_SECRET. |
query_state() |
Per managed group: present, gid, local_name, members, admins (when OPA answers), whether an IaC-owned enrollment token exists on the login project (enrollment_token), and, when the workload fields are set, workload (role, policy, connection). A call that failed is {present: false, error: ...}; a 404 is {present: false}. Read-only. |
alias_registration_script(names) |
The root script that rewrites the AltNames block of /etc/sft/sftd.yaml (kept last in the file) with names and restarts sftd only when the block changed, printing the contract's ALIASES_CHANGED or ALIASES_UNCHANGED (server_aliases.py). The core decides which names a machine gets back after launch (the bare declared name, the pool alias, the provider's ip-... label) and runs the script over the runtime's session; this is the only place the file and the agent are named. |
container_runtime_objection() |
Why an image owned by an Okta group may not bake on a container runtime: sftd needs systemd, sshd, a reachable address and a cloud identity. validate refuses such an image with this sentence. |
workload_access_detail(condition, expected, real) |
The sentence the state query prints for each of the contract's WORKLOAD_* conditions (role absent, policy absent or diverged, connection absent, a draft, or unreadable), in OPA's words and naming the CI setup guide's step; the comparison itself is the core's. |
credential_environment_prefixes() |
("OKTA_",): preflight reports an OKTA_* variable that is set but empty. |
can_query_servers(), registered_servers(group), retire_servers_named(group, hostname) |
The OPA server registry of <group>_rg_login: every enrolled server as {id, hostname, address, canonical_name, alt_names, instance_id}, or None when OPA could not be asked; retirement DELETEs every registration of a hostname and returns the ids, raising when the registry cannot be read. A DELETE answered 404 counts as already gone, judged by the error's status code and never by the text of the message, so a 500 whose text mentions 404 is a failure. |
can_manage_workload_access(), workload_access_expected(group), workload_access_state(group), ensure_workload_access(group) |
The CI login policy: true only with both workload_connection and workload_role set; what the configuration expects; what OPA holds; and the reconcile that creates, updates or leaves the <group>_v1_security_policy_ci policy as a copy of <group>_v1_security_policy_user with the role as its only principal and admin-level permissions forced off. |
prune_stale_attachments(tofu, run, cwd) |
The runner step: lists tofu state, keeps every oktapam_user_group_attachment the declaration still has, asks OPA about each dropped one and removes from state, after a backup, only those OPA no longer holds. |
validate_attributes, query_attributes, attribute_conflicts |
OPA attribute validation and read-only reads through opa_attributes.py and opa_gids.py. |
The OPA API client (OpaGidResolver)
obtains a service token from POST /v1/teams/{team}/service_token and
reads .../groups/{group}/attributes, .../groups/{group}/users,
.../users/{user}/attributes, .../attributes/conflicts, the resource
group / project / enrollment-token / server listings under
/v1/teams/{team}/resource_groups/..., .../security_policy,
.../workload-roles (a hyphen) and .../connections/workloads. It writes
only through DELETE .../servers/{id}, POST .../security_policy and PUT .../security_policy/{id}. Token values are never fetched or returned. A
listing longer than one page is followed through its Link: <...>; rel="next" header to the last page. The policy derivation is pure code
in
workload_policy.py.
OktaTfGroupRoBuilder (okta-tf-ro)
okta_opa_tf_group_ro_builder.py.
Extends OktaTfGroupBuilder, so the identity-type hooks that shape an
image (prerequisites, activation, launch parameters) are inherited
unchanged. What differs:
-
The hooks that would ask OPA about a group or point at something the managed root makes answer the read-only truth instead:
manages_groups()isFalse, so the identity read-model records each groupmanaged: falseand neither the never-destroy rule nor the state query's drift rule applies to it;query_state()returns{}without asking OPA;enrollment_token_reference()isNone, because this root emits nogroup_enrollment_tokensoutput;can_query_servers()andcan_manage_workload_access()areFalse;query_attributes()andattribute_conflicts()raiseNotImplementedError, which the attribute plan reports as "cannot query attributes". Because none of these answers is the managed parent's, a group on this builder never readsmissing [HARD]. -
When a managed builder of the same identity type exists, it comes first for the image bake and the in-bake verification, whatever the names sort to, so the prerequisites comment names the managed builder.
-
generate_items_before: the same scaffolding, but only when at least one group is attached. -
generate_items_during: one file,<ws>-group-generation-groups-data.tf, holding adata "okta_group"lookup per group (sorted by name,provider = okta.<ws>). No module calls, no resources, no outputs file. -
get_commands_to_run_after: generation-timefmt,init,validate;plan(in the private mirror) only on a real run withokta/oktacredentials in the environment. No deferred commands, so nothing from this builder reachesrun-identity.sh. Nothing at all when no groups are attached.
OktaTfUserBuilder (okta-tf)
okta_opa_tf_user_builder.py.
Extends
UserBuilderBase.
Every hook keys on the user-generation phase and does nothing when no
users are attached.
generate_items_beforeregisters the workspace, registers every user'sfirst_name,last_name,email(andlogin, when it is not the email) as sensitive values (a declared-encrypted value becomes alocal.sensitive["<key>"]reference), then writes<ws>/user-generation/<ws>-user-generation.tf(header,terraform {}with theoktaprovider andexternalwhen a decrypting data source is needed, the aliasedprovider "okta"block, thedata "external" "sensitive"block andlocals), a-<ws>-vars.tffile only when a provider declared variables (theoktaprovider declares none), and<ws>-user-generation.tfbackend.hcl.get_commands_to_run_before: nothing.generate_items_during: for each user (sorted by name), a managed user (is_managed: the item'smanaged, else the builder'sdefault_managed(),Truehere) gets anokta_userresource in<ws>-user-generation-users.tfand a lookup that depends on it in<ws>-user-generation-users-data.tf; an unmanaged user gets only an eager lookup in the-users-data.tffile.get_commands_to_run_during: nothing.generate_items_after: nothing.get_commands_to_run_after: generation-timefmt,init,validate, plusmaterializeandplanin the private mirror on a real run withokta/oktacredentials present. No deferred commands.pre_finalize_phase/post_finalize_phase: not overridden.
validate_attributes and query_attributes cover OPA user attributes.
Group membership is not emitted here: the group root attaches members by
username string.
OktaTfUserRoBuilder (okta-tf-ro)
okta_opa_tf_user_ro_builder.py.
Extends OktaTfUserBuilder and changes two things: default_managed() is
False, so every user is a lookup unless the item says otherwise; and
validate_user reports an error for any item with managed: true. The
emission and commands are the parent's.
Emission
Real file names from the golden emission under
tests/instance/golden/generated/identity,
produced by the fixture's oktagroups (okta-tf), okta-groups-ro
(okta-tf-ro, one group, readers) and
okta-tf-users (okta-tf-ro) builders, all bound to the fixture's
local-dev state backend. The read-only group root is
okta-groups-ro/group-generation/: the scaffolding file and
okta-groups-ro-group-generation-groups-data.tf with one
data "okta_group" "readers":
| File | Content |
|---|---|
| oktagroups/group-generation/oktagroups-group-generation.tf | terraform {} with oktapam and external, backend "local" {}, provider "oktapam" (key and secret as var. references) and provider "external", both alias = "oktagroups". |
| oktagroups-group-generation-oktagroups-vars.tf | The two sensitive variables. |
oktagroups-group-generation-group-basic.tf, -coops.tf, -secofs.tf, -stofs.tf, -tcmet.tf |
One module "group_<label>" call each. |
| oktagroups-group-generation-outputs.tf | The gid shim data source and the three outputs. |
| oktagroups-group-generation.tfbackend.hcl | Backend partial configuration (path = ... for the local backend). |
| okta-tf-users/user-generation/okta-tf-users-user-generation.tf | terraform {} with okta and external, backend "local" {}, provider "okta" with org_name/base_url, the data "external" "sensitive" block carrying the ciphertexts (a derived address as <name>@ENC[age:...]), and locals. |
| okta-tf-users-user-generation-users-data.tf | One data "okta_user" lookup per user. No -users.tf file: the builder is read-only, so no resources exist. |
| okta-tf-users-user-generation.tfbackend.hcl | Backend partial configuration. |
| run-identity.sh | The deferred commands: only the oktagroups root's rm, init, prune-attachments, plan and gate-plan, each entered through cs-image-system materialize (the fixture has apply_identity: false, so no apply-check or apply). |
The system's identity read-model
(meta-state/identity.yaml)
records, per group, the builder, identity_type: okta,
gid_policy: creation-only, managed, is_root, members and admins as
this plugin reports them, plus a workload record (the expected
connection, role and policy names, and after a real apply the reconcile's
action, id, role_id and run) when the builder names the workload
objects.
Example configuration
From tests/instance/fixture/cfg/group-builders.yml:
group_builders:
- name: oktagroups
is_default: true
type: okta-tf
executable: open-tofu-1
state_configuration: local-dev
org: "noaa"
team: "nos-coastal-modeling-cloud-sandbox"
# required: the posix group builder that makes these groups exist on
# the machines of their images (or `none` for no posix configuration)
posix: posix-local
required_providers:
- name: oktapam
source: okta/oktapam
version: '>= 0.6.3'
# the delegate `posix:` names, from the posix identity plugin
- name: posix-local
type: posix
user_builders:
- name: okta-tf-users
is_default: true
type: okta-tf-ro
executable: open-tofu-1
state_configuration: local-dev
org: "noaa"
team: "nos-coastal-modeling-cloud-sandbox"
email_as_username: false
email_domain: ENC[age:...] # example.invalid
default_user_email_template: "{{ user.name }}@{{ builder.email_domain }}"
required_providers:
- name: okta
source: okta/okta
version: '>= 6.0'
posix: is required on every okta-tf group builder (see
posix in the configuration reference): an
entry without it fails validate. posix-local is a group builder of the
posix identity plugin, declared in
the same file; it takes no further fields.
The live tree adds workload_connection: "github-cs-image-system" and
workload_role: "cs-image-system-ci" to the group builder and binds both
roots to the default (S3) backend.
The gateway_selector those groups use comes from the global
configuration
(cfg/_config.yml):
config.okta_gateway_selector: "environment=staging".
The groups these builders act on live in
tests/instance/fixture/groups. Member
and admin entries are bare OPA usernames, declared encrypted (ENC[age:...]
ciphertexts, shortened here); the golden shows their decrypted values. From
test-group.yaml:
groups:
- name: basic
is_root: true
is_default: false
description: "Root admin group with access to everything"
admins:
- ENC[age:...] # avery.alpha
tags:
environment: production
- name: coops
is_default: false
description: "CO-Ops group"
members:
- ENC[age:...] # avery.alpha
- ENC[age:...] # casey.charlie
admins:
- ENC[age:...] # avery.alpha
- ENC[age:...] # casey.charlie
tags:
environment: test
Because basic is the root group, its admin avery.alpha appears in the
admins list of every other group's module call. A user entry from
users.yaml has the same
shape: name, first_name, last_name (all required, all declared
encrypted) and an optional email; with no email, the builder's template
derives <name>@example.invalid.
Commands
This plugin mounts two things on the console script through the contract's
cs_image_system.commands entry-point group
(cli.py); both exist exactly
when the plugin is installed, and cs-image-system --help lists them.
cs-image-system workload-- what CI's workload login needs:describe [--env]prints the team's workload connection and role, the team and the API address from the first group builder that names them (--envas shell exports:OPA_WORKLOAD_CONNECTION,OPA_WORKLOAD_ROLE,SFT_TEAM,OPA_ADDR);tokenpresents the GitHub Actions run's OIDC token to the connection and prints the OPA token it yields, and nothing else, on standard output (both tokens masked in the job log; the names come from the environment, and the configuration loads only when one is missing);probedoes the same, discards the token and says whether the ROLE reaches a standing machine of a managed group (sft resolveas the workload). The sub-app loads the configuration only when a command needs it.cs-image-system verify login [<instance>...] [--runtime <rt>] [--timeout] [--record-only]-- the login proof: oversft sshfor this plugin's groups, as the workload whenOPA_TOKENis set, else as the enrolled client. The command is the core's one callback (cs_image_system.engine.commands.login_proof.verify_login_command: which instances are targets, the skips, the record inmeta-state/login-proofs.yaml), shared with the posix-identity plugin: each identity plugin mounts the same callback and the console script mounts it once, so the proof is there whichever of them a tree installs, and each plugin's checks run through the one driver.
Prerequisites and integration
Everything below exists outside the system. Where the plugin finds each item is named next to it; the general rules are in docs/OPERATIONS.md ("Credentials contract") and the system's docs/CONFIGURATION.md (section 14, environment variables).
An Okta org and an OPA team. The org name goes in org, the team
name in team. The OPA API is reached at api_host (default
https://<org>.pam.okta.com); the Okta org itself at
<org>.<okta_base_url> through the okta/okta provider. Both are HTTPS
from wherever the configuration loads, plans or is queried: the load itself
makes no network call, but a real run's generation-time plan, every
deferred command, the gid shim, the state query and verify login do.
An OPA API service key pair for the team, with its resource_admin
role. The oktapam terraform provider reads it through two sensitive
variables, var.<team>_key and var.<team>_secret, filled from the
environment variables TF_VAR_<team>_key and TF_VAR_<team>_secret (the
team name with every non-alphanumeric character replaced by _; the
live team is nos_coastal_modeling_cloud_sandbox). key: and secret:
left at default on the builder resolve to those variables at finalize
and the load checks that the environment variables exist whenever oktapam
is among required_providers (a ValueError when one is missing). A literal (or ENC[age:...]) key: and
secret: bypass the variables. The plugin's own API client
(credentials_from_env in opa_gids.py)
takes the same TF_VAR_<team>_* pair, or OKTAPAM_KEY / OKTAPAM_SECRET
as a generic fallback; it never reads key:/secret: from the builder.
What the pair must be able to do, all under /v1/teams/<team>/: mint a
service token; read group and user attributes and attribute conflicts;
list group users; list resource groups, their projects, the projects'
enrollment tokens and servers (servers answer only under the resource
group path, .../resource_groups/<rg>/projects/<prj>/servers; the
team-level /projects/... path answers 401 Missing capability); delete a
server registration; list, create and update security policies; list
workload roles and workload connections. The pair lives only in the two
checkouts' .envrc files and in the repository secrets TF_VAR_NOS_KEY /
TF_VAR_NOS_SECRET (exported under the team-specific names by CI).
An Okta API services app for the okta/okta provider (user lookups,
read-only group lookups). The provider reads OKTA_API_CLIENT_ID,
OKTA_API_SCOPES, OKTA_API_PRIVATE_KEY, OKTA_API_PRIVATE_KEY_ID (or
OKTA_API_TOKEN for SSWS) from the environment itself; nothing about
them enters the configuration or the emission. The load checks only that
one of OKTA_API_PRIVATE_KEY, OKTA_API_TOKEN, OKTA_ACCESS_TOKEN is
set when okta is among the providers, warns otherwise, and the builder
then skips its generation-time plan. The scopes stay at
okta.users.read okta.groups.read (the lookups pass skip_roles and
skip_groups); DPoP stays off (the provider does not support it); the
*.manage scopes stay ungranted. Any provider argument the app needs
(client_id, scopes, private_key_id, ...) may also be written under
the provider entry's config: and passes through untouched.
A terraform binary. executable: names a cfg/executables.yml entry
whose binary is tofu or terraform; the version floor is that entry's
requirement, checked at validate and before every run. The
providers okta/oktapam (>= 0.6.3 in the fixture and the live tree;
0.7.1 is the version the code's behaviour is written against),
okta/okta (>= 6.0) and hashicorp/external (unpinned, added by the
builder) are fetched by tofu init from the public registry.
The terraform module okta_opa_module, found at
config.module_source_base (default ../tfmodules, relative to the
configuration root) or where config.module_sources names it. This
plugin ships the module as package data under
src/cs_image_system/okta_opa_plugin/tfmodules/,
declared through the cs_image_system.modules entry point; a configuration
tree holds a copy (init-config or cs-image-system modules --write
writes it) or sources it from elsewhere.
A state backend. state_configuration names a state_backends:
entry, or default picks the default one. The s3 backend needs an AWS
session for the profile it names (the live tree); the local backend
(the fixture) needs nothing. Backend blocks and the .tfbackend.hcl file
are emitted only when config.use_state_backends is true. The instance
roots read the identity root's outputs through terraform_remote_state,
so the instance lifecycle needs read access to the same location.
The cs-image-system CLI on PATH of whoever runs terraform: the
generated roots call cs-image-system decrypt --json (the sensitive
values) and cs-image-system identity export-gids (the gid shim) as
data "external" programs, and the deferred script calls materialize,
prune-attachments, state-migration, gate-plan and apply-check.
just and uv run provide it; a hand tofu plan inside a generated root
needs it too, together with CSIS_CONFIG_IDENTITY.
The age identity in CSIS_CONFIG_IDENTITY: the rosters (name,
first_name, last_name, members, admins, email_domain) are
ENC[age:...] values in the live tree, every load decrypts them, and
terraform decrypts the emitted ciphertexts at plan time through the same
identity. Without it the load refuses.
The machines. Base images that declare identity_types: [okta] reach
https://dist.scaleft.com during the bake (the OktaPAM package
repository), and Debian vendor images get curl and gnupg installed
first. An instance enrolls with sftd at launch using the token the
identity root minted (read by the instance root as a sensitive
remote-state reference; TF_VAR_enrollment_token is the explicit
override), advertises its private address, and must be reachable through
an OPA gateway matching gateway_selector (the live value is
environment=staging, from config.okta_gateway_selector) that wears the
gateway's security group.
The workload connection and role, only when CI is to log in: made by
hand once in the OPA admin console following
the CI setup guide, section 3.5, then named on
the okta-tf group builder as workload_connection and workload_role.
The system reads both by name and never writes them. The bootstrap's
Okta and OPA section (okta = cs_image_system.okta_opa_plugin.bootstrap:okta_section in the
cs_image_system.bootstrap entry-point group) checks them -- present,
ACTIVE, requiring this repository, the role bound and pinned to the
production branch -- and checks the Okta API services app by asking for
a token with its own key and scopes (okta_app_check), so the generated
README lists exactly what is still by hand. verify login and
just ci-login-proof additionally need Okta's sft client on the machine
that runs them (and OPA_TOKEN to log in as the workload).
Global keys read from cfg/_config.yml: apply_identity (the apply
gate for the group root and for the CI policy reconcile),
okta_gateway_selector (the gateway_selector fallback),
module_source_base, use_state_backends.
Configuration reference
The field-by-field contract. Types are the Python annotations; a default
of required means the load refuses without it.
Every okta-tf / okta-tf-ro builder (the workspace mixin)
| Field | Type | Default | Meaning |
|---|---|---|---|
org |
str |
required | Okta org name; api_host and the okta provider's org_name derive from it. |
team |
str |
required | OPA team; names the credential variables and the oktapam_team provider argument; the API client's /v1/teams/<team>/ path. |
key |
EncryptedStr |
default |
OPA API key for the oktapam provider block. default becomes var.<team>_key (backed by TF_VAR_<team>_key); a literal is quoted into HCL; an ENC[age:...] value is emitted as local.sensitive["oktapam_key"]. Read only when oktapam is a declared provider. |
secret |
EncryptedStr |
default |
As key, for the secret. |
api_host |
str |
https://{{ this.org }}.pam.okta.com |
Optional. OPA API host for the provider block, the gid shim query, the state query and every API call; unset, it is https://<org>.pam.okta.com. |
okta_base_url |
str |
okta.com |
The okta provider's base_url when the provider entry's config: does not set one. Accepted, not read on a builder without an okta provider. |
default_user_status |
str |
STAGED |
okta_user.status for enabled managed users. Read only by a user builder emitting a managed user; accepted, not read on group builders and on okta-tf-ro user builders with no managed: true item. Not validated by the plugin. |
required_providers |
list | [] |
Provider entries (below). Nothing checks that a group root names oktapam or a user root names okta; a root with no provider emits no provider block and the plugin logs a warning about the missing okta binding when it emits data sources. |
state_configuration |
str |
default |
Foreign key to a state_backends: entry; default binds the default backend. |
A required_providers entry:
| Field | Type | Default | Meaning |
|---|---|---|---|
name |
str |
required | oktapam, okta, or another provider (passed through with a warning). |
source |
str |
required | e.g. okta/oktapam. |
version |
str |
required | The constraint written into terraform { required_providers }. |
config |
mapping | {} |
Provider arguments. For okta used as-is plus org_name/base_url defaults; for oktapam ignored (the block is built from the fields above). |
Group builders (okta-tf, okta-tf-ro)
| Field | Type | Default | Meaning |
|---|---|---|---|
gateway_selector |
str | None |
None |
The login project's gateway_selector in every module call; None falls back to config.okta_gateway_selector, and with neither the argument is omitted. Accepted, not read by okta-tf-ro (no module call). |
account_discovery |
bool |
True |
The login project's account_discovery. Accepted, not read by okta-tf-ro. |
workload_connection |
str | None |
None |
The team's workload connection, by name. Read only when workload_role is set too. |
posix |
str | None |
none: required on okta-tf |
The posix group builder that makes this builder's groups exist on the machines of their images, by name, or none for no posix configuration. Absent or empty is refused at validate, as is a name that is no declared group builder or one not of type posix. With a name: every instance image of these groups bakes the delegate's login hook, and every applying instance run creates each group on its running machines with OPA's gid (asked read-only) and writes its member list -- members and admins, the root group's admins merged as OPA has them; OPA's agent makes each account at a login and drops its groups when it deletes it, so the hook adds the user at every login. With none, validate and the state query note each group that stays off its machines. Not read by okta-tf-ro. |
posix_ssh_keys |
bool |
False |
Opt-in: the login hook also installs each member's declared public_keys: as their authorized_keys -- a key path beside OPA's certificates. |
workload_role |
str | None |
None |
The team's workload role, by name. With both set the builder manages one CI login policy per managed group and reports the three objects in the state query. |
User builders (okta-tf, okta-tf-ro)
The base UserBuilderModel fields, all read here:
| Field | Type | Default | Meaning |
|---|---|---|---|
default_user_email_template |
str |
{{ user.name }} |
Renders email for a user that declares none; {{ builder.email_domain }} inside it is replaced by email_domain before rendering. |
default_user_description_template |
str |
User {{ user.name }} / {{ user.email }} |
Renders description; never emitted. |
email_domain |
str | None |
None |
The domain half of a derived address; may be ENC[age:...], in which case every derived address carries that ciphertext in the emission. |
email_as_username |
bool |
True |
name must equal email case-insensitively (a blank name is set from the email); a mismatch aborts the load. |
Common builder fields (BuilderModel)
| Field | Type | Default | Meaning |
|---|---|---|---|
name |
str |
required | The workspace name: the root directory, the provider alias, the state key, the module call's providers binding. |
type |
str |
required | okta-tf or okta-tf-ro. |
executable |
str | None |
None |
The executables: entry to run; required in practice (a missing one fails the first command with Executable '...' not found). |
is_default |
bool |
False |
The builder an item's type: default selects (loader). |
aliases |
set[str] |
{} |
Other names an item may select this builder by (loader). |
description, config, gitignore, tags |
Accepted, not read by this plugin. | ||
parameters |
Refused at load. |
Items
Group (groups:) fields the plugin reads: name, members, admins,
is_root, include_root_group_in_admins, unmanaged, attributes.
Accepted, not read by the plugin: gid, description, tags, config,
in_both, is_default, aliases.
User (users:) fields the plugin reads: name, first_name,
last_name, email, is_enabled, managed, attributes, and the
okta_user profile arguments (middle_name, mobile_phone,
honorific_prefix, honorific_suffix, title, display_name,
nick_name, profile_url, second_email, primary_phone,
street_address, city, state, zip_code, country_code,
postal_address, preferred_language, locale, timezone,
user_type, employee_number, cost_center, organization,
division, department, manager_id, manager) when set and truthy.
Accepted, not read: description (rendered by the base, never emitted),
is_service_account, public_keys, tags, config.
Attribute declarations (attributes:) accept exactly: on a group
unix_gid (int), unix_group_name (str), windows_group_name (str); on
a user unix_uid (int), unix_gid (int), unix_user_name (str),
windows_user_name (str). An int must be at least 1024 and not a bool; a
str must not be blank. They are planned and probed, never written.
Variations
okta-tfversusokta-tf-roas a group builder.okta-tfemits one module call per group, the outputs file, the vars file, and the deferred plan-gate-apply sequence, and always scaffolds its root even with no group.okta-tf-roemits onlydata "okta_group"lookups, no outputs and no deferred commands, and emits nothing at all with no group; it needs theoktaprovider instead ofoktapam, so noTF_VAR_<team>_*check fires for it. The image hooks (prerequisites, activation, launch parameters) are inherited; the hooks that read or point into OPA are not: a group on anokta-tf-robuilder is recorded asidentity_type: okta,gid_policy: creation-onlyandmanaged: false, the state query asks OPA nothing about it, no enrollment token is referenced for it, and it has no CI login policy.okta-tfversusokta-tf-roas a user builder. The emission is one code path chosen per item bymanaged:okta-tfdefaults to managed (anokta_userresource plus a lookup thatdepends_onit);okta-tf-rodefaults to lookup-only (an eager lookup that must resolve at plan) and refusesmanaged: trueatvalidate.managed: true|false|nullon a user.nulltakes the builder's default; an explicit value overrides it. A managed user's status isdefault_user_status, orSUSPENDEDwhenis_enabled: false.unmanaged: trueon a group. The module call becomes a one-line comment, the group leaves the outputs, and the runner's pre-plan step (prune-attachments) removes from state, after a backup, whatever the state still holds undermodule.group_<label>. Nothing is destroyed. The step decides from the state it lists when it runs, not from the identity read-model, because generation rewrites that file on every dry run and everyrecord. A tree on an older release can still plan such a group for destruction (the gate refuses it); the stage index places the rule. A dry run logs which groups the step will look for. The CI policy reconcile andquery_stateskip an unmanaged group.include_root_group_in_admins: false. The root group's admin usernames are not merged into this group'sadmins, in the module call and in whatprune_stale_attachmentstreats as declared. The state query still expects the merge (a base rule), so such a group showsadminsdrift.is_root: true. That group'sadminsare merged into every other group's admins. The root group's own module call is a normal one.key/secretatdefault, literal, orENC[age:...].default:var.<team>_*in the provider block, two variables in the vars file, and the load checks that theTF_VAR_<team>_*variables exist. A literal: quoted into the provider block (a secret in the emission; do not). AnENC[age:...]value: emitted aslocal.sensitive["oktapam_key"]/["oktapam_secret"]fed by the root'sdata "external" "sensitive"block, and no check fires. The API client ignores all three and reads the environment.- Encrypted versus clear roster values. A
first_name,last_name,email(or a bare-namelogin) that was declared encrypted is emitted aslocal.sensitive["<key>_<label>"]and its ciphertext goes into the root's decrypting data source; a clear value is emitted as a literal. A derived address inherits the encryption ofemail_domain(<name>@ENC[age:...]). Usernames inmembers/adminsare always emitted in clear (a public join key by decision). gateway_selectorset, unset with a global, unset without. The module argument is the builder's value, elseconfig.okta_gateway_selector, else omitted (the module passesnulland OPA assigns no gateway).oktapamversusoktainrequired_providers.oktapam: two sensitive variables, the credentials in the provider block by variable, theTF_VARcheck at load.okta: no variables,org_nameandbase_urlin the block, a warning at load withoutOKTA_API_*credentials, andplanskipped at generation while they are absent.- Dry run versus real run (the
--dry-rundefault versus--no-dry-run). Dry:init -backend=false, no generation-time plan, no state touched, no mirror; the deferred script is still written in full. Real:init -reconfigure -backend-config=..., thenmaterializeand a plan in the private mirror (-refresh=falsefor the group root); the deferred script executes afterwards in-process, and the after-apply hooks run. apply_identityoff, on, or a list. Off: the runner ends atgate-plan, the CI policy reconcile does not run, and the read-model'sworkloadrecord stays at what is expected. On (true, or a list naming this builder):apply-checkandapplyfollow the gate, and after the runner every managed group's CI policy is created, updated or left alone, the outcome written under the group inidentity.yaml.apply-checkre-reads the flag at execution and refuses (exit 3) when it is off by then.- Workload fields set versus unset. Unset:
can_manage_workload_access()is false, the read-model carries noworkloadkey, the state query reports nothing about policies, andverify loginskips every instance of the group ("names no workload connection and role"). Set: the reconcile runs after a real apply, the state query reads policies, roles and connections, andverify loginproves the login. attributes:declared on any group or user versus none. Declared: the load validates names and types, the identity lifecycle writesgenerated/identity/attributes-plan.json, and the runner ends withidentity-attributes --probe --dry-run-apply(a read-only probe; a write exits 4 by design). None: no plan file, no probe.os_familydebian/ubuntuversus anything else. The base-image prerequisites use the apt repository path (with acurl/gnupgbootstrap) or the rpm/yum path.use_state_backendstrue versus false. True: abackend "<type>" {}stanza and the.tfbackend.hclfile; the runner'sinitcarries-backend-config=. False: neither;initruns bare and the state is local to the root.--migrate-state <ws>on a real run. The runner sequence begins withstate-migration begin, inits with-migrate-state -force-copy, plans with-detailed-exitcodeand records the move after the gate (a base mechanism the identity roots share).
What it tests and verifies
At load (model construction and finalize). Pydantic refuses a wrong
type or a missing org/team; the base model refuses parameters.
UserBuilderBase.add_user_to_builder raises ValueError when
email_as_username is true and name differs from email. The
workspace's finalize() checks that TF_VAR_<team>_key and
TF_VAR_<team>_secret exist when oktapam is declared and key/secret
are at default (a ValueError that fails every configuration load,
validate included; a real raise, not an assert, so it still fires
under python -O), and logs a warning when okta is declared and no
OKTA_API_* credential is set. Verdicts: an exception with the message
below, or a log line Okta builder <name>: no okta/okta credentials in the environment (...); 'plan' will be skipped for this workspace. The okta-opa-plugin README, "Prerequisites and integration", lists what each root needs.
At validate (and before every run). The plugin's item checks run
through the base's validate_identity_items
(identity_attributes.py):
OktaTfUserRoBuilder.validate_user refuses managed: true;
validate_attributes refuses unknown names, wrong types, ids below 1024
and blank strings on groups and users. Around them the base checks that a
group the read-model recorded as managed is still declared
(validation_rules.py),
that every base image's identity_types names a registered plugin, that
an instance image's group resolves to an identity type its base declares,
and, when the instance-image lifecycle is requested with apply_instances
on, that no declared instance's canonical hostname is already registered
in its group's OPA registry (registered_servers; an unreadable registry
is a refusal, not a free name). Verdict: validate prints one - <error>
line per rule and exits 1; a run refuses before generating.
At generation. Every root runs tofu fmt, tofu init and tofu validate in-process, so an emission the provider rejects fails the run
there. On a real run the group root plans with -refresh=false and the
user and read-only group roots plan, all in the private mirror with the
credentials of the environment; a lookup that finds no user, or a
provider that cannot authenticate, fails the plan and the run. The
builders log a warning when they emit a data source or resource with no
okta provider bound. After the identity lifecycle generates, the base
writes meta-state/identity.yaml from this plugin's answers and
generated/identity/attributes-plan.json when attributes are declared.
At apply (the deferred runner). prune-attachments lists the state
the root is bound to. First, for every group marked unmanaged: true:
if the state holds anything under module.group_<label>, the state is
backed up and the module is removed from it (... is unmanaged and the state still holds N of its resource(s); they leave tofu state before the plan and nothing is destroyed: state rm module.group_<label>); if it
holds nothing, nothing happens and no backup is taken. Then the
attachments: when an attachment in state is no longer declared it
asks OPA (group_users) and removes only those OPA no longer holds, after
state-migration backup pulled the state to
_private/state-backups/<ws>.backup-<run>.tfstate; a failed list, backup
or removal exits non-zero and the runner stops before its plan; a silent
OPA removes nothing. The run log names every attachment and why (... was dropped from group ... and OPA no longer holds it; its attachment leaves tofu state before the plan: state rm ..., or ... OPA still holds it; the plan will show the destroy). Then plan -out=tfplan, gate-plan (exit 3
on any destroy not whitelisted, a stale or missing plan file) and, with the
flag on, apply-check (exit 3 when the flag is off now) and apply. When
attributes are declared, identity-attributes --probe --dry-run-apply
reads every planned item's live attributes and the team's conflict report
and prints would set: ... lines; it never writes.
After apply. With apply_identity on and the workload fields set, the
base's workload_access.py
calls ensure_workload_access for every managed group and records
{action: created|updated|unchanged|failed, policy, id, role_id, run}
under the group's workload key in meta-state/identity.yaml; a failure
is an ERROR log line (Group <g>: its CI login policy was NOT reconciled (...); the CI login proof for this group fails until it is), never fatal
to the apply that already happened. When an instance is decommissioned,
the base's launch_params.py
calls retire_servers_named for its recorded hostname and logs the
retirement or an ERROR naming the stale server.
In the state query (state query [--strict], every run's first step;
state_query.py).
query_state reads every managed group's <group>_user attributes,
members, the <group>_admin members, the login project's enrollment
tokens and, with the workload fields set, the policies, roles and
connections. The base turns it into: missing [HARD] when OPA answered
404 for the group; missing (not hard) when the group has no gid;
missing [HARD] when no IaC-owned enrollment token stands on the
project; changed when members or admins differ from the read-model;
missing when the workload role is unknown to OPA or the CI policy is
absent, changed when the CI policy no longer mirrors the user policy
(with the differing leaves named); a note: when the connection is
absent, still a DRAFT, or of unknown status; and unavailable: groups/<g>: <error> when the call failed (a 401, no network, no
credentials), which is never drift. Verdicts land in
generated/state-report.json and on the console; --strict exits 1 on
any drift but stale and on any unavailable: line; a plain run refuses
only on [HARD] drift.
In the login proof (verify login, just ci-login-proof, the sft
leg of cloud-verify; login_proof.py).
For each standing instance of a group whose builder names the workload
objects: the machine is running, exactly one registration answers to its
hostname (registered_servers), sft resolve succeeds, id runs over
sft ssh. Verdicts go to meta-state/login-proofs.yaml; a failure exits 1.
In the images. verify_commands (sftd present, disabled, no token)
become in-bake assertions of every base image declaring okta, and
activation_verify_commands (the tx.group label, sftd enabled) of every
instance image, through the base's
image_tests.py; a
failing line fails the bake.
In the gid shim. identity export-gids answers terraform's data "external" query from the OPA Attributes API; a requested group with no
unix_gid makes the command exit 1 with export-gids: identity plugin 'okta' reported no gid for groups [...], which fails the plan or apply
that asked. Nothing is ever invented.
tests/test_bootstrap_okta.py holds the bootstrap's Okta and OPA
section: the entry point and the gate (wanted where an okta-tf group
builder is), placeholders refused by name, the reference shape reading
clean, names found by what they require, every failed check becoming its
guide step, nothing standing, observed checks asked again and refused
when the world cannot be asked, the root gaining no terraform, the
client assertion verified with the public key, and the app check's three
outcomes.
When it fails
Incidents that have happened, with their cause and fix, are recorded on INCIDENTS.md; what follows keeps each failure's symptom, its meaning and what to do.
Two refusals come first because every tree meets them once, when its
okta-tf group builders first need a posix: line
(the stage index places the rule):
| Symptom | Meaning | Do |
|---|---|---|
group builder <b>: `posix:` is required at validate |
the okta-tf group builder has no posix: line |
add posix: <a posix group builder> (declare one: - name: posix-local, type: posix) or posix: none |
group builder <b>: `posix: <x>` names no declared group builder / ... names a group builder of identity type '<t>' |
the name is wrong, or names a builder that is not posix | name a declared type: posix group builder |
Instance <i>: the accounts script of group <g> could not be made: ... in an applying run's log |
OPA could not be asked for the group's gid (the key pair, the network) | fix the credentials; the next applying run makes the group |
note: group <g>: its builder <b> says posix: none ... |
the team chose no posix configuration | nothing, if that is the choice; the group's storage subtree stays owned by a bare gid |
Failures by symptom: what each means and what to do. Each names the symptom as the operator sees it, what it means, where to look and what to do; the general rules are in docs/OPERATIONS.md and the CI setup guide.
-
An identity plan wants to create
oktapam_user_group_attachmentresources that already stand in OPA. The memberships exist out of band and the provider would error on apply. Repair:tofu importeach live attachment first; the import id is<group>|<username>(a/separator is rejected); zero OPA writes, then a plan reading "No changes". Rule: never let a plan create an attachment that already exists (OPERATIONS "Adopt out-of-band group membership"). -
An enrollment token deleted out of band. The identity plan ERRORS at refresh (oktapam 0.7.1 cannot plan the recreate); the state query shows
groups/<g>: missing ... IaC-owned launch enrollment token missing from the identity provider ... [HARD]and every run refuses. Repair:tofu state rmthe token resource in the group's module, then a gated identity apply mints a new one (a new value; instances launched before it keep the old token and are not affected). The state query'senrollment_tokenprobe is the only witness. -
STALE PLANFILE(exit 3) fromgate-plan. The plan file is older than the root's newest*.tf: a failed plan left an oldertfplan, which the gate refuses rather than apply, and the runner starts every root withrm -f tfplanso a stale file never survives into the next sequence. Rerun the sequence so a fresh plan is written. -
Okta builder oktagroups is missing a key value. Expected to find environment variable TF_VAR_nos_coastal_modeling_cloud_sandbox_key ...Every configuration load finalizes the workspace and checks the pair, so any command that loads the tree (validate,run,state query,verify) dies with thisValueError; a test that passes on your local machine because it inherits the developer's.envrchas nothing in CI. Repair:source .envrc(or export the two variables); in CI the secretsTF_VAR_NOS_KEY/TF_VAR_NOS_SECRET. -
no okta/okta credentials in the environmentfrom finalize while the variable is set. The value is the empty string, which a checkout missing.envrcexports; the warning is exactly what an empty value produces, and a green job can then run nothing. The CI gate names every missing or empty secret and fails, andpreflightexits 2 on any credential-shaped variable (OKTA_*,TF_VAR_*, ...) that is set but empty. A job's conclusion is never proof its steps ran. -
unavailable: groups/<g>: HTTP 401 Unauthorizedfor every group. The API answered 401: an unsourced.envrc, or the wrong or lapsed key pair. A failed call is{present: false, error: "HTTP 401 Unauthorized"}and reportedunavailable, nevermissing ... [HARD], so a lapsed pair cannot read as standing groups deleted; only an answered 404 ismissing. A 401 or "no gid" means the wrong or lapsed key pair: check which pair the environment exports (the last export wins) and rotate in the OPA console if it expired. -
Several registrations of one hostname;
sft ssh <name>cannot choose. Every relaunch of an instance enrolls another server under the same canonical name unless the old registration is retired. Servers answer only under/resource_groups/<rg>/projects/<prj>/servers(GET200,DELETE204; the team-level/v1/teams/<team>/projects/...path answers401 Missing capability), which the resolver walks from the resource-group and project names (<g>_rg,<g>_rg_login) to their ids. A decommission or replacement retires the registration (anERRORnaming the hostname when it cannot:Instance <n>: its OPA registration as '<h>' was NOT retired (...); a stale server will answer to that name until it is deregistered by hand), and a run that can launch refuses a claimed or unreadable name (could not check whether canonical hostname ... is already claimed ... refusing to launch on silence). Duplicates that already stand are deleted by hand in the OPA console. -
The run that would create the CI policies is refused because their absence reads as drift. Workload drift is never hard:
missingfor an absent role (workload role '...' named in the configuration is not known to OPA; the operator creates it (CI_SETUP.md section 3.5 section 2)) or an absent policy (CI login policy '...' is absent; an identity run with apply_identity creates it ...),changedfor a policy that no longer mirrors (... the next identity apply rewrites it -- <leaf>: <standing> != <desired>). A strict query still fails on them; the identity apply is the repair. -
GET /v1/teams/<team>/workload_rolesanswers 404. The path is hyphenated,workload-roles, as Okta's PAM SDK carries it; the connections path isconnections/workloads. A 404 from either listing surfaces asunavailable:in the state query and asOPA's security policies or workload roles could not be readfrom the reconcile. -
HTTP 400 Bad Requestfrom a policy write. The API's explanation is in the response body, so_sendraisesPOST /v1/teams/.../security_policy: HTTP 400 Bad Request -- <body>; read the body. A stored rule carriessecurity_policy_id, the one field on which a copy differs from its original, so the comparison strips OPA's bookkeeping ids at every depth. -
Every derived user lookup fails on a real run. The emission carries
<name>@ENC[age:...]addresses, so a plan run ingenerated/searches Okta for the ciphertext. The plan (and the runner) run in the private mirror aftercs-image-system materialize .; a handtofu planingenerated/identity/...reproduces the failure. Plan in_private/identity/...instead, withCSIS_CONFIG_IDENTITYandcs-image-systemonPATH. -
sft resolve --quietexit 126 with no output. The client wanted a browser: run by hand it means an expired client session (sft loginfirst); as the workload it meansOPA_TOKENis missing or was refused. The login proof recordsthe client has no session .... -
user "x" is not present within group "g"from the provider at refresh; the plan never runs. A user removed from a group's roster after being removed in OPA makes the provider ERROR instead of planning the destroy. Every identity runner therefore carriesprune-attachmentsbetweeninitandplan, backing the state up first. Three rules shape that step: the read-model written at generation outlives a failed runner (it says the membership is already gone; onlytofu state listis a witness); the CLI's load changes directory to the configuration root, so a runner step must act in the directory it was invoked from (a backup pulled from the wrong directory says "nothing to keep" and lets the removal run unbacked); and a pipe totailmasks the bar's exit code. If the plan still errors this way, the membership is one OPA still holds: either restore the roster entry or remove the member in OPA and rerun. -
A replacement's old registration claims the new machine's alias.
retire_servers_namedruns for the machine a replacement retires, and the alias pass waits for a machine launched in the same run to enroll before writingAltNames; the symptom means the retirement logged itsNOT retirederror. Deregister the stale server by hand under the resource-group path. -
Debian vendor images without
curlorgnupg. The apt path ofbase_image_prerequisitesinstalls them first. The rpm path needs nothing beyondrpmandyum.
Failures the code raises:
OPA credentials for team '<team>' not found in the environment (TF_VAR_<team>_key/TF_VAR_<team>_secret or OKTAPAM_KEY/OKTAPAM_SECRET)(ValueErrorfromcredentials_from_env): the gid shim exits 1 with it (export-gids: ..., failing the plan); the state query reports the builderunavailable;registered_serversanswersNone(a launch refuses on it);prune-attachmentslogs... OPA cannot be asked whether it still holds them (...); nothing is removedand continues.OPA service_token response carried no bearer_token: the key pair authenticated but the response had no token; same surfaces as above.okta gid shim query must carry 'team' and 'api_host': a hand-writtendata "external"query; the emitted one always carries both.identity plugin 'okta' reported no gid for groups [...](exit 1 fromexport-gids): the group's<group>_userOPA group has nounix_gidattribute yet, typically before the first apply created it, or the name differs. The plan that depends ondata.external.group_gidsfails; apply the identity root first, or check the group name in OPA.user '<u>': builder <b> is okta-tf-ro (read-only) and cannot manage users; move the user to an okta-tf builder(validate, exit 1).group '<g>': unknown OPA attribute 'x' (known: [...]),... must be int, got ...,... is below the reserved range (1024),... must not be empty(validate, exit 1); the same forms foruser '<u>'.identity attributes: the provider reports conflicts; refusing: [...](exit 3) andwriting identity attributes is disabled (DESIGN Q7 not confirmed); N change(s) were NOT applied(exit 4) fromidentity-attributes.workload role '<r>' is not known to OPA; the operator creates it (CI_SETUP.md section 3.5, step 2),workload role '<r>' carries no id,user policy '<g>_v1_security_policy_user' is absent; the identity apply creates it, and the CI policy is a copy of it,OPA's security policies or workload roles could not be read(RuntimeErrorfromensure_workload_access): logged as theERRORabove and recorded asaction: failedwith the message under the group'sworkloadkey; the next real identity run retries.OPA login project for group '<g>' not found; cannot retire <id>(ValueErrorfromretire_server) and any non-404 error from theDELETE: the decommission logs theNOT retirederror and completes; deregister by hand under the resource-group path. A 404 is recognised by the error's status code and never by the text of the message, so a 500 whose text mentions 404 is not recorded as a retirement.OPA could not be asked for group '<g>''s servers; registration of '<h>' NOT retired(RuntimeErrorfromretire_servers_named): same handling.Identity builder <ws>: 'state list' failed in <dir>; nothing is removed from stateand'state rm <addr>' failed; the runner stops here(exit 1 fromprune-attachments, stopping the runner before its plan); the backup step's own refusals (not an initialised root, a pull that fails, a location holding no state) stop it the same way.prune-attachments: no group builder named '<b>'(exit 2): the runner script names a builder the configuration no longer has; regenerate.Group builder <ws> has no configured 'okta' provider; emitted data sources will rely on a default provider configuration that this workspace does not generate(and the user builder's twin, a warning): the root will failtofu validate; add theoktaprovider entry.No transform for provider '<p>' on <Model>; passing its config through(warning): a provider other thanoktapam/oktawas declared; itsconfig:is emitted verbatim.Sensitive value '<key>' registered twice with different ciphertexts in workspace '<ws>'(HclConfigConflictError): two items produced the same sensitive key with different markers (two users whose labels collide,avery.alphaandavery_alpha); rename one.Executable '<e>' not found for builder '<ws>' of type '<t>'(ValueError):executable:names noexecutables:entry.Builder <b> sets email_as_username, but user name '<n>' != email '<e>'(ValueErrorat load).identity: group '<g>' was managed by the system but is missing from the YAML; groups never leave the configuration (keep the entry with 'unmanaged: true' ...)(a base rule at validate, exit 1).apply_identity is false NOW in <cfg>/_config.yml for root '<ws>' -- this runner script was generated when it allowed the apply; not applying.(exit 3 fromapply-check): the flag changed since generation; regenerate or turn it back on.login proof FAILED for <instance>: one registration: '<h>' has 2 registrations: .../resolves: sft resolve <h>: exit N -- .../login: sft ssh <h> --command id: exit N -- ...(exit 1 fromverify login, the record inmeta-state/login-proofs.yaml): a duplicate hostname, a machine that never enrolled, a deactivated or absent CI policy, a role condition the run does not match.
Related
- Base models extended: group_builder.py, user_builder.py, builder_model.py; items read: group.py, user.py.
- Base builder classes: builder_base_group.py, builder_base_user.py.
- Base code that calls this plugin's hooks:
read_models.py
(the identity read-model),
state_query.py
(drift rules),
workload_access.py
(the CI policy reconcile),
launch_params.py
(launch parameters, the enrollment token, the registry),
identity_attributes.py
(attributes),
identity_gids.py
(the gid shim command),
login_proof.py
(
verify login), state_migration.py (the state backup), and the CLI in cli.py. - Library:
hashicorp-utils --
collector.py
(providers, variables, backends, sensitive references),
blocks.py
(HCL rendering),
roots.py
(
TerraformRootMixin, the gated apply sequence). - Terraform module called: tfmodules/okta_opa_module (main.tf, variables.tf, outputs.tf).
- Manuals: this repository's docs/CONFIGURATION.md (the builders' fields), the system's docs/CONFIGURATION.md (sections 11.5, 11.6, 13, 14), docs/OPERATIONS.md ("CI logs in through the policy the system manages", "The state query", "Credentials contract", "The gid shim", "Rules: Identity"), docs/DESIGN.md (N1, N7, N19, section D), the CI setup guide, section 3.5.
- Tests: tests/ -- the module call, the workspace mixin, the
resource emitters, the four builder roots, the gid shim, the server
registry and the workload policy; the
prune-attachmentsrunner step in tests/test_stale_attachments.py.
Metadata
Release files for cs-image-system-okta-opa-plugin 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| cs_image_system_okta_opa_plugin-0.2.0.tar.gz | 132.0 kB | Without provenance | Details for cs_image_system_okta_opa_plugin-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| cs_image_system_okta_opa_plugin-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for cs_image_system_okta_opa_plugin-0.2.0-py3-none-any.whl |
Total release size: 241.7 kB
Release files / cs_image_system_okta_opa_plugin-0.2.0.tar.gz
| Download URL | cs_image_system_okta_opa_plugin-0.2.0.tar.gz |
|---|---|
| Size | 132.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
5fe8f8a8ef278bbeaad8e729b4747edaaf4a6006685e55b4847ae2a7277253d8
|
|
BLAKE2b-256 checksum How to use checksums |
14c7591e166ad4bf8f9dd5112b34d84023fe000ee2381d294bc14cb90f61b6a2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / cs_image_system_okta_opa_plugin-0.2.0-py3-none-any.whl
| Download URL | cs_image_system_okta_opa_plugin-0.2.0-py3-none-any.whl |
|---|---|
| Size | 109.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
b81afda8d77ea9c81977a9305e86454d88a0c0cf78f8417ecf702f30170836ad
|
|
BLAKE2b-256 checksum How to use checksums |
dcf2a9664e66eb89e8491d3e6ac75205e508124e992f0baee323540a03e03fb6
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for cs-image-system-okta-opa-plugin 0.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.