Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

requirements.authoring.credentials

Requirements index · View definition

evidence Valid

Requirement

Bedrock configurations MAY supply credentials containing nonempty access_key_id, secret_access_key, and optional nonempty session_token. Ollama and OpenAI configurations MAY supply a nonempty api_key. Habeas MUST reject a Bedrock record combining explicit credentials with aws_profile, and an Ollama or OpenAI record combining api_key with api_key_env.

Explicit credentials MUST be passed directly to the selected provider without changing process environment variables or writing credential files. Saved explicit values MUST round-trip; credentials resolved from profiles or the environment MUST NOT be serialized back. Debug output, configuration diagnostics, usage records, and initial prompts MUST NOT include credential values. TOML diagnostics MUST NOT echo credential-containing source lines. A configuration file containing explicit credentials MAY be read as source; its credential values MUST be redacted under cite requirements.authoring.redaction. Validation MUST report a workspace habeas.toml present in the Git index that contains explicit credentials, naming the file and the credential fields and recommending credential-source references, because committed credentials leak.

Documentation MUST discourage literal credentials in workspace files and recommend AWS profiles or environment-variable references. Examples MUST use placeholders and explain that workspace files may be committed or read as source when explicitly allowed.

Rationale

The reviewed tests cover every testable obligation in requirements.authoring.credentials. I found no gap.

Accepted shapes and rejections

  • tests/configuration.rs#fn[explicit_credentials_round_trip_but_diagnostics_and_debug_redact_them] rejects Bedrock credentials combined with aws_profile. It also rejects Ollama api_key combined with api_key_env, and empty access_key_id, secret_access_key, session_token and api_key.
  • tests/configuration.rs#fn[openai_configuration_preserves_model_and_resolves_credentials] rejects OpenAI api_key combined with api_key_env, and an empty api_key.
  • The same test covers the OpenAI case of api_key with api_key_env through UserConfig::parse.

Direct passing of credentials

  • src/authoring/providers.rs#mod[tests]/fn[explicit_bedrock_credentials_reach_the_sdk_without_the_default_chain] checks that the SDK config exposes the exact access key, secret and session token.
  • tests/authoring_cli.rs#fn[authoring_uses_nearest_workspace_configuration_without_a_user_file] checks that the Ollama key reaches the request headers.
  • tests/authoring_cli.rs#fn[openai_key_only_profile_defaults_to_sol_and_accepts_overrides] checks the OpenAI Bearer header.
  • The CLI test also checks that neither configuration file is rewritten and that no user configuration file is created.
  • The “no process environment change” clause concerns process-wide state, and no test in the project sets that up. I treat it as exempt.

Round-trip and no serialization of resolved values

  • The explicit_credentials_round_trip_but_diagnostics_and_debug_redact_them test asserts parse(to_toml(config)) == config for explicit Bedrock, Ollama and OpenAI credentials.
  • tests/configuration.rs#fn[ollama_authentication_resolves_separately_and_rejects_missing_values] and fn[openai_configuration_preserves_model_and_resolves_credentials] show that environment-resolved keys are absent from the serialized output.
  • src/authoring/providers.rs#mod[tests]/fn[omitted_bedrock_profile_and_region_use_standard_sdk_resolution] shows that profile-resolved credentials are not serialized and that the config is unchanged.

No credential values in outputs

  • Debug output is covered by the explicit_credentials_round_trip_but_diagnostics_and_debug_redact_them test, which formats the config with {:?} and checks it for secrets.
  • Configuration diagnostics are covered by the same test, which feeds both a TOML syntax error (a trailing token after the value) and schema errors (a wrong type, a credentials string) to WorkspaceConfig::parse and UserConfig::parse. It asserts that the errors never contain PRIVATE_ or the numeric value.
  • tests/configuration.rs#fn[evidence_configuration_ignores_unused_authoring_settings_and_detects_credentials] asserts the same for load_workspace_config.
  • Usage records, stdout and stderr are covered by authoring_uses_nearest_workspace_configuration_without_a_user_file and openai_key_only_profile_defaults_to_sol_and_accepts_overrides.
  • Initial prompts, habeas reads, ripgrep results and citation prompts are covered by src/authoring/tools.rs#mod[tests]/fn[model_inputs_reads_searches_and_citation_prompts_are_redacted] and src/authoring/mod.rs#mod[tests]/fn[site_prompts_exclude_credentials_from_source_and_configuration].

Configuration file readable as source, with values redacted

  • src/authoring/access.rs#mod[tests]/fn[workspace_configuration_with_credentials_is_readable_unless_disallowed] shows the file is readable.
  • src/redaction/tests.rs#fn[configuration_credential_fields_are_redacted_by_name_whatever_their_values] and the tools test show the values replaced by [REDACTED:api_key] and similar markers.
  • The detailed redaction behavior belongs to the cited requirements.authoring.redaction, which I did not reassess.

Validation of committed credentials

  • src/evidence.rs#mod[tests]/fn[committed_workspace_credentials_are_reported_but_untracked_ones_are_not] covers the following:
    • An indexed tools/habeas.toml is reported, and an unindexed one is not.
    • The report names the file and the full credential field paths.
    • The report recommends aws_profile and api_key_env.
    • The report does not echo the secret values.
    • Staging the root file raises the count to two.
    • A credential-free file is not reported.

Documentation obligations The documentation obligations (discourage literal credentials, use placeholders, explain commit and read-as-source risk) are carried out by the book text carrying {impl} references in md/requirements/authoring.md and md/reference.md. They have no test obligation here.

Inputs

Tests

Input 3: outline src/authoring/access.rs mod[tests]/fn[discovery_considers_indexed_files_except_exclusions_including_credential_configuration]
  • File: src/authoring/access.rs
  • Selector: mod[tests]/fn[discovery_considers_indexed_files_except_exclusions_including_credential_configuration]
  • Kind: fn
  • src/authoring/access.rs:766–815
    // {test}`requirements.references.discovery`
    // {test}`requirements.authoring.credentials`
    #[test]
    fn discovery_considers_indexed_files_except_exclusions_including_credential_configuration() {
        let root = tempfile::tempdir().unwrap();
        let root = fs::canonicalize(root.path()).unwrap();
        for file in [
            "src/lib.rs",
            "src/staged.rs",
            "src/deleted.rs",
            "src/untracked.rs",
            "crates/a/target/out.rs",
            "evidence/x.json",
            "docs/book/page.md",
        ] {
            let path = root.join(file);
            fs::create_dir_all(path.parent().unwrap()).unwrap();
            fs::write(path, "text\n").unwrap();
        }
        fs::write(
            root.join("habeas.toml"),
            "version = 1\n[authoring.configs.cloud]\nprovider = \"bedrock\"\napi_key = \"secret\"\n",
        )
        .unwrap();
        git(&root, &["init", "--quiet"]);
        git(&root, &["add", "-f", "."]);
        git(&root, &["rm", "--cached", "--quiet", "src/untracked.rs"]);
        fs::remove_file(root.join("src/deleted.rs")).unwrap();
        let sources = DiscoverySources::load(&root).unwrap();
        let mut errors = Vec::new();
        let files: Vec<_> = sources
            .files(&mut errors)
            .into_iter()
            .map(|path| path.strip_prefix(&root).unwrap().to_owned())
            .collect();
        assert!(errors.is_empty(), "{errors:?}");
        assert_eq!(
            files,
            [
                Path::new("docs/book/page.md"),
                Path::new("habeas.toml"),
                Path::new("src/lib.rs"),
                Path::new("src/staged.rs"),
            ]
        );
        assert_eq!(
            sources.untracked().unwrap(),
            [root.join("src/untracked.rs")]
        );
    }
Input 4: outline src/authoring/access.rs mod[tests]/fn[workspace_configuration_with_credentials_is_readable_unless_disallowed]
  • File: src/authoring/access.rs
  • Selector: mod[tests]/fn[workspace_configuration_with_credentials_is_readable_unless_disallowed]
  • Kind: fn
  • src/authoring/access.rs:974–996
    // {test}`requirements.authoring.credentials`
    // {test}`requirements.configuration.evidence_paths`
    // {test}`requirements.authoring.read_denial`
    // {test}`requirements.authoring.source_tools`
    #[test]
    fn workspace_configuration_with_credentials_is_readable_unless_disallowed() {
        let root = tempfile::tempdir().unwrap();
        let config = "version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'fixture'\napi_key = 'TEST_KEY'\n";
        fs::write(root.path().join("habeas.toml"), config).unwrap();
        let access = SourceAccess::load(root.path()).unwrap();
        assert!(access.file(root.path(), Path::new("habeas.toml")).is_ok());
        fs::write(
            root.path().join("habeas.toml"),
            format!("{config}\n[evidence]\ndisallow = ['habeas.toml']\n"),
        )
        .unwrap();
        let error = SourceAccess::load(root.path())
            .unwrap()
            .file(root.path(), Path::new("habeas.toml"))
            .unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
        assert!(!error.to_string().contains("TEST_KEY"));
    }
Input 5: outline src/authoring/mod.rs mod[tests]/fn[site_prompts_exclude_credentials_from_source_and_configuration]
    // {test}`requirements.authoring.credentials`
    // {test}`requirements.authoring.redaction`
    #[test]
    fn site_prompts_exclude_credentials_from_source_and_configuration() {
        let token = crate::redaction::tests::github_token();
        let source = crate::sites::tests::SOURCE.replace(
            "fn check_two() {}",
            &format!("fn check_two() {{ let credential = \"{token}\"; }}"),
        );
        let project = crate::sites::tests::project(crate::sites::tests::RULE, &source);
        fs::write(project.path().join("habeas.toml"), "version = 1\n[authoring.configs.local]\nbackend = 'openai'\napi_key = 'SITE_CONFIG_SECRET'\n").unwrap();
        let subject = AuthoringSubject::parse("sites:requirements.rule/src/lib.rs#fn[check_two]");
        let sources = subject.sources(project.path()).unwrap();
        let prompt = initial_prompt(&sources).unwrap().joined();
        assert!(prompt.contains("[REDACTED:GitHub Token]"));
        assert!(!prompt.contains(&token));
        assert!(!prompt.contains("SITE_CONFIG_SECRET"));
    }
Input 6: outline src/authoring/providers.rs mod[tests]/fn[explicit_bedrock_credentials_reach_the_sdk_without_the_default_chain]
    // {test}`requirements.authoring.credentials`
    // {test}`requirements.authoring.rig_configuration_mapping`
    // {test}`requirements.authoring.configuration_precedence`
    #[tokio::test]
    async fn explicit_bedrock_credentials_reach_the_sdk_without_the_default_chain() {
        let config: BedrockConfig = toml::from_str("model = 'test'\nregion = 'us-west-2'\n[credentials]\naccess_key_id = 'TEST_ACCESS'\nsecret_access_key = 'test-secret'\nsession_token = 'test-session'\n").unwrap();
        let sdk = bedrock_sdk_config(&config).await;
        let credentials = sdk
            .credentials_provider()
            .unwrap()
            .provide_credentials()
            .await
            .unwrap();
        assert_eq!(credentials.access_key_id(), "TEST_ACCESS");
        assert_eq!(credentials.secret_access_key(), "test-secret");
        assert_eq!(credentials.session_token(), Some("test-session"));
        assert_eq!(sdk.region().unwrap().as_ref(), "us-west-2");
    }
Input 7: outline src/authoring/providers.rs mod[tests]/fn[omitted_bedrock_profile_and_region_use_standard_sdk_resolution]
    // {test}`requirements.authoring.configuration_precedence`
    #[tokio::test]
    #[allow(deprecated)] // The non-deprecated profile-file names live in `aws-runtime`.
    // {test}`requirements.configuration.serialization`
    // {test}`requirements.authoring.credentials`
    async fn omitted_bedrock_profile_and_region_use_standard_sdk_resolution() {
        use aws_config::profile::profile_file::{ProfileFileKind, ProfileFiles};
        let dir = tempfile::tempdir().unwrap();
        let config_file = dir.path().join("config");
        let credentials_file = dir.path().join("credentials");
        std::fs::write(
            &config_file,
            "[default]\nregion = eu-west-1\n[profile other]\nregion = ap-south-1\n",
        )
        .unwrap();
        std::fs::write(
            &credentials_file,
            "[default]\naws_access_key_id = DEFAULT_KEY\naws_secret_access_key = DEFAULT_SECRET_VALUE\n\
             [other]\naws_access_key_id = OTHER_KEY\naws_secret_access_key = OTHER_SECRET_VALUE\n",
        )
        .unwrap();
        let files = ProfileFiles::builder()
            .with_file(ProfileFileKind::Config, &config_file)
            .with_file(ProfileFileKind::Credentials, &credentials_file)
            .build();
        let standard = || {
            aws_config::defaults(aws_config::BehaviorVersion::latest()).profile_files(files.clone())
        };
        let habeas = |text: &str| {
            let config: BedrockConfig = toml::from_str(text).unwrap();
            let before = toml::to_string(&config).unwrap();
            let loading = bedrock_sdk_loader(&config, standard()).load();
            async move {
                let sdk = loading.await;
                let credentials = sdk
                    .credentials_provider()
                    .unwrap()
                    .provide_credentials()
                    .await
                    .unwrap();
                let after = toml::to_string(&config).unwrap();
                assert_eq!(before, after);
                assert!(!after.contains(credentials.access_key_id()));
                assert!(!after.contains(credentials.secret_access_key()));
                sdk
            }
        };
        async fn resolved(sdk: aws_config::SdkConfig) -> (Option<String>, String) {
            let key = sdk
                .credentials_provider()
                .unwrap()
                .provide_credentials()
                .await
                .unwrap()
                .access_key_id()
                .to_owned();
            (sdk.region().map(|region| region.to_string()), key)
        }

        // Omitted values resolve exactly as the SDK would with no override.
        let omitted = resolved(habeas("model = 'test'").await).await;
        assert_eq!(omitted, resolved(standard().load().await).await);
        // An explicit profile is the one the SDK resolves from.
        let profile = resolved(habeas("model = 'test'\naws_profile = 'other'").await).await;
        assert_eq!(
            profile,
            resolved(standard().profile_name("other").load().await).await
        );
        // An explicit region overrides whatever the profile or environment says.
        let region =
            resolved(habeas("model = 'test'\naws_profile = 'other'\nregion = 'us-east-2'").await)
                .await;
        assert_eq!(region.0.as_deref(), Some("us-east-2"));
        assert_eq!(region.1, profile.1);
    }
Input 8: outline src/authoring/tools.rs mod[tests]/fn[model_inputs_reads_searches_and_citation_prompts_are_redacted]
    // {test}`requirements.authoring.redaction`
    // {test}`requirements.authoring.credentials`
    // {test}`requirements.authoring.source_tools`
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.authoring.mandatory_inputs`
    // {test}`requirements.authoring.citation_prompt`
    // {test}`requirements.authoring.fixme_inputs`
    #[test]
    fn model_inputs_reads_searches_and_citation_prompts_are_redacted() {
        let root = project();
        let token = crate::redaction::tests::github_token();
        fs::write(
            root.path().join("habeas.toml"),
            "version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\napi_key = 'plain ollama key'\n",
        )
        .unwrap();
        fs::write(
            root.path().join("src/lib.rs"),
            format!(
                "// {}\nfn client() -> &'static str {{\n    \"{token}\"\n}}\n\n// :::{} requirements.ready\n// Defaults to {token}.\n// :::\nfn helper() {{}}\n\n// :::{{fixme}} requirements.ready\n// Missing check for {token}.\n// :::\nfn gap() {{}}\n",
                role("test", "requirements.ready"),
                "{cite}"
            ),
        )
        .unwrap();
        git(root.path(), &["init", "--quiet"]);
        git(root.path(), &["add", "."]);
        let leaks = |value: &Value| {
            let text = value.to_string();
            text.contains(&token) || text.contains("plain ollama key")
        };
        // Mandatory inputs, and so the initial and verification prompts.
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let mandatory = Value::Array(sources.mandatory_inputs().to_vec());
        assert!(!leaks(&mandatory), "{mandatory:#}");
        assert!(mandatory.to_string().contains("[REDACTED:GitHub Token]"));
        let prompt = super::super::initial_prompt(&sources).unwrap().joined();
        assert!(!prompt.contains(&token), "{prompt}");
        assert!(
            prompt.contains("Missing check for [REDACTED:GitHub Token]."),
            "{prompt}"
        );
        assert!(!prompt.contains("fn gap()"), "{prompt}");
        // A habeas read of the configuration file and a line range.
        let read = dispatch(&sources, "habeas", &json!({"file":"habeas.toml","item":""})).unwrap();
        assert!(!leaks(&read.result), "{:#}", read.result);
        assert!(
            read.result["input"]["text"]
                .as_array()
                .unwrap()
                .contains(&json!("api_key = '[REDACTED:api_key]'"))
        );
        let lines = dispatch(
            &sources,
            "habeas",
            &json!({"file":"src/lib.rs","line_start":1}),
        )
        .unwrap();
        assert!(!leaks(&lines.result), "{:#}", lines.result);
        // Search results, even for a pattern matching the credential itself.
        for pattern in ["ollama", "gh[p]_", "Defaults"] {
            let search = dispatch(&sources, "ripgrep", &json!({"pattern": pattern})).unwrap();
            assert!(
                !search.result["matches"].as_array().unwrap().is_empty(),
                "{pattern}"
            );
            assert!(!leaks(&search.result), "{pattern}: {:#}", search.result);
        }
        // A citation review's inputs and its commentary in the prompt.
        let citation =
            AssessmentSources::prepare_citation(root.path(), "src/lib.rs", "fn[helper]").unwrap();
        assert!(!leaks(&Value::Array(citation.mandatory_inputs().to_vec())));
        let prompt = super::super::initial_prompt(&citation).unwrap().joined();
        assert!(!prompt.contains(&token), "{prompt}");
        assert!(
            prompt.contains("Defaults to [REDACTED:GitHub Token]."),
            "{prompt}"
        );
    }
Input 9: outline src/evidence.rs mod[tests]/fn[committed_workspace_credentials_are_reported_but_untracked_ones_are_not]
  • File: src/evidence.rs
  • Selector: mod[tests]/fn[committed_workspace_credentials_are_reported_but_untracked_ones_are_not]
  • Kind: fn
  • src/evidence.rs:2272–2307
    // {test}`requirements.authoring.credentials`
    #[test]
    fn committed_workspace_credentials_are_reported_but_untracked_ones_are_not() {
        let temp = fixture();
        let root = temp.path();
        fs::create_dir_all(root.join("tools")).unwrap();
        let config = "version = 1\n[authoring.configs.cloud]\nbackend = 'bedrock'\nmodel = 'm'\n[authoring.configs.cloud.credentials]\naccess_key_id = 'PRIVATE_ACCESS'\nsecret_access_key = 'PRIVATE_SECRET'\n";
        fs::write(root.join("habeas.toml"), config).unwrap();
        fs::write(root.join("tools/habeas.toml"), config).unwrap();
        crate::authoring::access::tests::git(root, &["init", "--quiet"]);
        crate::authoring::access::tests::git(root, &["add", "book.toml", "src", "tools"]);
        let committed = |errors: &[String]| {
            errors
                .iter()
                .filter(|error| error.contains("contains explicit credentials"))
                .cloned()
                .collect::<Vec<_>>()
        };
        let report = super::validate_repository(root).unwrap();
        let found = committed(&report.errors);
        assert_eq!(found.len(), 1, "{:#?}", report.errors);
        assert!(found[0].starts_with("tools/habeas.toml: "), "{}", found[0]);
        assert!(found[0].contains("`authoring.configs.cloud.credentials.access_key_id`, `authoring.configs.cloud.credentials.secret_access_key`"), "{}", found[0]);
        assert!(found[0].contains("aws_profile") && found[0].contains("api_key_env"));
        assert!(!found[0].contains("PRIVATE_"), "{}", found[0]);
        // Staging the workspace file reports it too; a credential-free one is fine.
        crate::authoring::access::tests::git(root, &["add", "habeas.toml"]);
        assert_eq!(
            committed(&super::validate_repository(root).unwrap().errors).len(),
            2
        );
        fs::write(root.join("tools/habeas.toml"), "version = 1\n[authoring.configs.cloud]\nbackend = 'bedrock'\nmodel = 'm'\naws_profile = 'dev'\n").unwrap();
        let found = committed(&super::validate_repository(root).unwrap().errors);
        assert_eq!(found.len(), 1);
        assert!(found[0].starts_with("habeas.toml: "));
    }
Input 10: outline src/redaction/tests.rs fn[configuration_credential_fields_are_redacted_by_name_whatever_their_values]
  • File: src/redaction/tests.rs
  • Selector: fn[configuration_credential_fields_are_redacted_by_name_whatever_their_values]
  • Kind: fn
  • src/redaction/tests.rs:53–113
// {test}`requirements.authoring.redaction`
// {test}`requirements.authoring.credentials`
#[test]
fn configuration_credential_fields_are_redacted_by_name_whatever_their_values() {
    let source = "version = 1\n\
        [authoring.configs.cloud]\n\
        backend = 'bedrock'\n\
        model = 'm'\n\
        [authoring.configs.cloud.credentials]\n\
        access_key_id = 'plainaccesskey'\n\
        secret_access_key = \"no prefix secret\"\n\
        session_token = '''\nsession\ntoken'''\n\
        [authoring.configs.local]\n\
        backend = 'ollama'\n\
        model = 'm'\n\
        api_key = 'ollama key'\n";
    let redacted = Redaction::of_file(Path::new("sub/habeas.toml"), source)
        .apply(source)
        .into_owned();
    assert_eq!(
        redacted,
        "version = 1\n\
        [authoring.configs.cloud]\n\
        backend = 'bedrock'\n\
        model = 'm'\n\
        [authoring.configs.cloud.credentials]\n\
        access_key_id = '[REDACTED:access_key_id]'\n\
        secret_access_key = \"[REDACTED:secret_access_key]\"\n\
        session_token = '''[REDACTED:session_token]\n\n'''\n\
        [authoring.configs.local]\n\
        backend = 'ollama'\n\
        model = 'm'\n\
        api_key = '[REDACTED:api_key]'\n"
    );
    assert_eq!(redacted.lines().count(), source.lines().count());
    let fields = credential_fields(source).unwrap();
    assert_eq!(
        fields
            .iter()
            .map(|field| field.setting.as_str())
            .collect::<Vec<_>>(),
        [
            "authoring.configs.cloud.credentials.access_key_id",
            "authoring.configs.cloud.credentials.secret_access_key",
            "authoring.configs.cloud.credentials.session_token",
            "authoring.configs.local.api_key",
        ]
    );
    // Inline tables are found by name too.
    let inline = "version = 1\n[authoring.configs.c]\ncredentials = { access_key_id = 'a1', secret_access_key = 's1' }\n";
    assert_eq!(
        Redaction::of_file(Path::new("habeas.toml"), inline).apply(inline),
        "version = 1\n[authoring.configs.c]\ncredentials = { access_key_id = '[REDACTED:access_key_id]', secret_access_key = '[REDACTED:secret_access_key]' }\n"
    );
    // The same text in a file that is not a configuration file has no
    // credential-shaped value, so it is unchanged.
    assert_eq!(
        Redaction::of_file(Path::new("notes.toml"), source).apply(source),
        source
    );
}
Input 11: outline tests/authoring_cli.rs fn[authoring_uses_nearest_workspace_configuration_without_a_user_file]
// {test}`requirements.configuration.workspace_location`
// {test}`requirements.authoring.configuration`
// {test}`requirements.configuration.workspace_structure`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.credentials`
// {test}`requirements.authoring.provider`
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.invocation`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.configuration.serialization`
#[test]
// {test}`requirements.configuration.documentation`
fn authoring_uses_nearest_workspace_configuration_without_a_user_file() {
    let server = Server::start(vec![reply(vec![call(
        "submit",
        "submit_judgment",
        json!({"determination":true,"rationale":"The supplied sources support the subject."}),
    )])]);
    let fixture = Fixture::new(&server.endpoint);
    fs::remove_file(fixture.config.join("habeas/config.toml")).unwrap();
    fs::write(
        fixture.project.join("habeas.toml"),
        "version = 1\n[authoring]\ndefault = 'missing-parent-choice'\n",
    )
    .unwrap();
    let nested = fixture.project.join("src/nested");
    fs::create_dir(&nested).unwrap();
    let workspace = nested.join("habeas.toml");
    fs::write(
        &workspace,
        format!(
            "version = 1\n[authoring]\ndefault = 'workspace'\n[authoring.configs.workspace]\npolicy = 'once'\nbackend = 'ollama'\nmodel = 'workspace-model'\nendpoint = '{}'\napi_key = 'WORKSPACE_LITERAL_KEY'\n",
            server.endpoint
        ),
    )
    .unwrap();
    let configurations = [fixture.project.join("habeas.toml"), workspace.clone()];
    let before = configurations
        .iter()
        .map(|path| fs::read(path).unwrap())
        .collect::<Vec<_>>();
    let output = fixture
        .command()
        .current_dir(&nested)
        .args(["author", SUBJECT])
        .output()
        .unwrap();
    assert!(output.status.success(), "{output:?}");
    // Running the configured feature rewrites neither configuration file,
    // and creates no user configuration.
    for (path, before) in configurations.iter().zip(&before) {
        assert_eq!(&fs::read(path).unwrap(), before, "{}", path.display());
    }
    assert!(!fixture.config.join("habeas/config.toml").exists());
    let requests = server.finish();
    assert_eq!(requests.len(), 1);
    assert_eq!(requests[0].body["model"], "workspace-model");
    assert!(requests[0].headers.contains("WORKSPACE_LITERAL_KEY"));
    assert!(
        !requests[0]
            .body
            .to_string()
            .contains("WORKSPACE_LITERAL_KEY")
    );
    let usage = fixture.usage();
    assert_eq!(usage["model"], "workspace-model");
    for text in [
        usage.to_string(),
        String::from_utf8_lossy(&output.stdout).into_owned(),
        String::from_utf8_lossy(&output.stderr).into_owned(),
    ] {
        assert!(!text.contains("WORKSPACE_LITERAL_KEY"), "{text}");
    }
}
Input 12: outline tests/authoring_cli.rs fn[missing_or_empty_api_key_env_fails_before_any_model_request]
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.credentials`
#[test]
fn missing_or_empty_api_key_env_fails_before_any_model_request() {
    let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
    listener.set_nonblocking(true).unwrap();
    let fixture = Fixture::new(&format!("http://{}", listener.local_addr().unwrap()));
    let config_path = fixture.config.join("habeas/config.toml");
    let original_config = fs::read_to_string(&config_path).unwrap();
    for backend in ["ollama", "openai"] {
        fs::write(
            &config_path,
            original_config.replace("backend = 'ollama'", &format!("backend = '{backend}'")),
        )
        .unwrap();
        for value in [None, Some("")] {
            let mut command = fixture.command();
            match value {
                None => command.env_remove("HABEAS_TEST_MODEL_KEY"),
                Some(value) => command.env("HABEAS_TEST_MODEL_KEY", value),
            };
            let output = command.args(["author", SUBJECT]).output().unwrap();
            let stderr = String::from_utf8_lossy(&output.stderr);
            assert!(!output.status.success(), "{value:?}: {stderr}");
            assert!(
                stderr.contains("HABEAS_TEST_MODEL_KEY"),
                "{value:?}: {stderr}"
            );
            assert!(
                matches!(listener.accept(), Err(error) if error.kind() == std::io::ErrorKind::WouldBlock),
                "{value:?}: the model endpoint was contacted"
            );
            assert_eq!(
                fs::read_to_string(&fixture.evidence).unwrap(),
                fixture.original
            );
        }
    }
}
Input 13: outline tests/authoring_cli.rs fn[openai_key_only_profile_defaults_to_sol_and_accepts_overrides]
// {test}`requirements.authoring.openai_defaults`
// {test}`requirements.authoring.credentials`
// {test}`requirements.authoring.adaptive`
#[test]
fn openai_key_only_profile_defaults_to_sol_and_accepts_overrides() {
    mock_server_waits_for_remaining_request_headers();
    for (extra, model, effort, max_tokens) in [
        ("", "gpt-6.1-sol", "low", 16_384),
        ("model = 'gpt-6-luna'\n", "gpt-6-luna", "low", 16_384),
        (
            "model = 'gpt-6-luna'\n[authoring.configs.api.options]\nmax_output_tokens = 8192\n[authoring.configs.api.options.reasoning]\neffort = 'medium'\n",
            "gpt-6-luna",
            "medium",
            8192,
        ),
    ] {
        let submit = json!({"determination":false,"rationale":"Fixture assessment."});
        let server = Server::start(vec![json!({
            "id":"resp_submit", "object":"response", "status":"completed",
            "model":model, "output":[{
                "type":"function_call", "id":"fc_submit", "call_id":"submit",
                "name":"submit_judgment", "arguments":submit.to_string(), "status":"completed"
            }],
            "usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}
        })]);
        let fixture = Fixture::new(&server.endpoint);
        // Only the endpoint is fixture-specific; policy/concurrency/model are optional.
        fs::write(fixture.config.join("habeas/config.toml"), format!(
            "version = 1\n[authoring]\ndefault = 'api'\n[authoring.configs.api]\nbackend = 'openai'\napi_key = '{AUTH}'\nendpoint = '{}'\n{extra}", server.endpoint)).unwrap();
        let output = fixture.run(&["author", SUBJECT]);
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        let requests = server.finish();
        assert_eq!(requests.len(), 1);
        assert_eq!(requests[0].body["model"], model);
        assert_eq!(requests[0].body["reasoning"]["effort"], effort);
        assert_eq!(requests[0].body["max_output_tokens"], max_tokens);
        assert!(requests[0].headers.contains(&format!("Bearer {AUTH}")));
        let usage = fixture.usage();
        assert_eq!(usage["model"], model);
        assert_eq!(usage["policy"], "once");
        assert!(!usage.to_string().contains(AUTH));
    }
}
Input 14: outline tests/configuration.rs fn[ollama_authentication_resolves_separately_and_rejects_missing_values]
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.credentials`
// {test}`requirements.configuration.serialization`
#[test]
fn ollama_authentication_resolves_separately_and_rejects_missing_values() {
    let config = UserConfig::parse(
        "version = 1\n[authoring.configs.remote]\nbackend = 'ollama'\nmodel = 'm'\napi_key_env = 'MODEL_KEY'",
        Path::new("config.toml"),
    ).unwrap();
    let BackendConfig::Ollama(ollama) =
        &config.authoring.as_ref().unwrap().configs["remote"].backend
    else {
        panic!("wrong backend")
    };
    assert!(ollama.api_key_from(|_| None).is_err());
    assert!(ollama.api_key_from(|_| Some(OsString::new())).is_err());
    assert_eq!(
        ollama
            .api_key_from(|name| (name == "MODEL_KEY").then(|| OsString::from("private-value")))
            .unwrap()
            .as_deref(),
        Some("private-value")
    );
    let serialized = config.to_toml().unwrap();
    assert!(serialized.contains("MODEL_KEY"));
    assert!(!serialized.contains("private-value"));
}
Input 15: outline tests/configuration.rs fn[evidence_configuration_ignores_unused_authoring_settings_and_detects_credentials]
  • File: tests/configuration.rs
  • Selector: fn[evidence_configuration_ignores_unused_authoring_settings_and_detects_credentials]
  • Kind: fn
  • tests/configuration.rs:476–517
// {test}`requirements.configuration.workspace_structure`
// {test}`requirements.configuration.evidence_paths`
// {test}`requirements.configuration.loading`
// {test}`requirements.authoring.credentials`
#[test]
fn evidence_configuration_ignores_unused_authoring_settings_and_detects_credentials() {
    let temp = tempfile::tempdir().unwrap();
    let path = temp.path().join("habeas.toml");
    fs::write(&path, "version = 1\n[evidence]\nallow = ['generated', '../shared']\ndisallow = ['generated/private']\n[authoring.configs.cloud]\nbackend = 'unknown'\ncredentials = 'DO_NOT_PRINT_THIS_CREDENTIAL'\n").unwrap();
    let policy = load_workspace_evidence(temp.path()).unwrap().unwrap();
    assert_eq!(policy.path, path);
    assert_eq!(policy.root, temp.path().canonicalize().unwrap());
    assert_eq!(
        policy.evidence.allow,
        vec![Path::new("generated"), Path::new("../shared")]
    );
    assert!(policy.contains_credentials);
    let error = load_workspace_config(temp.path()).unwrap_err().to_string();
    assert!(!error.contains("DO_NOT_PRINT_THIS_CREDENTIAL"), "{error}");

    fs::write(&path, "version = 1\n[authoring]\ndefault = 123\n").unwrap();
    assert!(
        !load_workspace_evidence(temp.path())
            .unwrap()
            .unwrap()
            .contains_credentials
    );
    assert!(load_workspace_config(temp.path()).is_err());
    for source in [
        "version = 2",
        "version = 1\nunknown = true",
        "version = 1\n[evidence]\nallow = ['']",
        "version = 1\n[evidence]\ndisallow = [42]",
        "version = 1\n[evidence]\nunknown = []",
    ] {
        fs::write(&path, source).unwrap();
        let error = load_workspace_evidence(temp.path())
            .unwrap_err()
            .to_string();
        assert!(error.contains(path.to_str().unwrap()), "{error}");
    }
}
Input 16: outline tests/configuration.rs fn[explicit_credentials_round_trip_but_diagnostics_and_debug_redact_them]
// {test}`requirements.authoring.credentials`
// {test}`requirements.authoring.configuration_serialization`
// {test}`requirements.configuration.serialization`
// {test}`requirements.configuration.loading`
// {test}`requirements.authoring.configuration_structure`
#[test]
fn explicit_credentials_round_trip_but_diagnostics_and_debug_redact_them() {
    let path = Path::new("habeas.toml");
    let source = "version = 1\n[authoring.configs.cloud]\nbackend = 'bedrock'\nmodel = 'm'\n[authoring.configs.cloud.credentials]\naccess_key_id = 'PRIVATE_ACCESS_KEY'\nsecret_access_key = 'PRIVATE_SECRET_KEY'\nsession_token = 'PRIVATE_SESSION'\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\napi_key = 'PRIVATE_OLLAMA_KEY'\n[authoring.configs.openai]\nbackend = 'openai'\napi_key = 'PRIVATE_OPENAI_KEY'\n";
    let config = WorkspaceConfig::parse(source, path).unwrap();
    let debug = format!("{config:?}");
    for secret in [
        "PRIVATE_ACCESS_KEY",
        "PRIVATE_SECRET_KEY",
        "PRIVATE_SESSION",
        "PRIVATE_OLLAMA_KEY",
        "PRIVATE_OPENAI_KEY",
    ] {
        assert!(!debug.contains(secret), "{debug}");
    }
    assert_eq!(
        WorkspaceConfig::parse(&config.to_toml().unwrap(), path).unwrap(),
        config
    );
    let BackendConfig::Ollama(local) = &config.authoring.as_ref().unwrap().configs["local"].backend
    else {
        panic!("wrong backend");
    };
    assert_eq!(
        local.api_key_from(|_| None).unwrap().as_deref(),
        Some("PRIVATE_OLLAMA_KEY")
    );
    for invalid_source in [
        "version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\napi_key = ['PRIVATE_OLLAMA_KEY']\n",
        "version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\napi_key = 'PRIVATE_OLLAMA_KEY' unexpected\n",
        "version = 1\n[authoring.configs.cloud]\nbackend = 'bedrock'\nmodel = 'm'\ncredentials = 'PRIVATE_SECRET_KEY'\n",
        "version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\napi_key = 123456789\n",
    ] {
        for error in [
            WorkspaceConfig::parse(invalid_source, path).unwrap_err(),
            UserConfig::parse(invalid_source, path).unwrap_err(),
        ] {
            let error = error.to_string();
            assert!(error.contains("habeas.toml"), "{error}");
            assert!(!error.contains("PRIVATE_"), "{error}");
            assert!(!error.contains("123456789"), "{error}");
        }
    }
    for invalid_source in [
        source.replace(
            "model = 'm'\n[authoring.configs.cloud.credentials]",
            "model = 'm'\naws_profile = 'p'\n[authoring.configs.cloud.credentials]",
        ),
        source.replace(
            "api_key = 'PRIVATE_OLLAMA_KEY'",
            "api_key = 'PRIVATE_OLLAMA_KEY'\napi_key_env = 'KEY'",
        ),
        source.replace(
            "secret_access_key = 'PRIVATE_SECRET_KEY'",
            "secret_access_key = ''",
        ),
        source.replace("access_key_id = 'PRIVATE_ACCESS_KEY'", "access_key_id = ''"),
        source.replace("session_token = 'PRIVATE_SESSION'", "session_token = ''"),
        source.replace("api_key = 'PRIVATE_OLLAMA_KEY'", "api_key = ''"),
    ] {
        assert!(WorkspaceConfig::parse(&invalid_source, path).is_err());
    }
}
Input 17: outline tests/configuration.rs fn[openai_configuration_preserves_model_and_resolves_credentials]
// {test}`requirements.authoring.configuration_serialization`
// {test}`requirements.authoring.credentials`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.configuration_structure`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.configuration.serialization`
#[test]
fn openai_configuration_preserves_model_and_resolves_credentials() {
    let source =
        "version = 1\n[authoring.configs.api]\nbackend = 'openai'\nmodel = 'account-model-id'\n";
    let path = Path::new("settings.toml");
    let config = UserConfig::parse(source, path).unwrap();
    let backend = &config.authoring.as_ref().unwrap().configs["api"].backend;
    assert_eq!(backend.model_ref().backend, BackendKind::Openai);
    assert_eq!(backend.model_ref().model, "account-model-id");
    let BackendConfig::Openai(openai) = backend else {
        panic!("wrong backend")
    };
    assert_eq!(openai.endpoint(), "https://api.openai.com/v1");
    assert!(openai.api_key_from(|_| None).is_err());
    assert_eq!(
        openai
            .api_key_from(|name| {
                assert_eq!(name, "OPENAI_API_KEY");
                Some("test-key".into())
            })
            .unwrap()
            .as_str(),
        "test-key"
    );
    let serialized = config.to_toml().unwrap();
    assert!(!serialized.contains("api_key"));
    assert_eq!(UserConfig::parse(&serialized, path).unwrap(), config);
    for extra in [
        "api_key = 'secret'\napi_key_env = 'KEY'",
        "api_key_env = ''",
        "api_key = ''",
        "[authoring.configs.api.options]\ninput = 'override'",
        "[authoring.configs.api.options]\ninstructions = 'override'",
    ] {
        assert!(UserConfig::parse(&format!("{source}{extra}\n"), path).is_err());
    }
    let mut custom = openai.clone();
    custom.endpoint = Some("https://example.invalid/v1".into());
    custom.api_key_env = Some("CUSTOM_OPENAI_KEY".into());
    assert_eq!(custom.endpoint(), "https://example.invalid/v1");
    assert!(custom.api_key_from(|_| None).is_err());
    assert!(custom.api_key_from(|_| Some("".into())).is_err());
    assert_eq!(
        custom
            .api_key_from(|name| {
                assert_eq!(name, "CUSTOM_OPENAI_KEY");
                Some("custom-key".into())
            })
            .unwrap(),
        "custom-key"
    );
}
Input 18: outline tests/live_bedrock.rs fn[credentials_available]
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.credentials`
fn credentials_available(config: &BedrockConfig) -> bool {
    tokio::runtime::Runtime::new().unwrap().block_on(async {
        let mut loader = aws_config::defaults(aws_config::BehaviorVersion::latest());
        if let Some(profile) = &config.aws_profile {
            loader = loader.profile_name(profile);
        }
        if let Some(region) = &config.region {
            loader = loader.region(aws_config::Region::new(region.clone()));
        }
        if let Some(credentials) = &config.credentials {
            loader = loader.credentials_provider(aws_sdk_bedrockruntime::config::Credentials::new(
                credentials.access_key_id.expose_secret(),
                credentials.secret_access_key.expose_secret(),
                credentials.session_token.as_ref().map(|value| value.expose_secret().to_owned()),
                None,
                "Habeas configuration",
            ));
        }
        let sdk = loader.load().await;
        let Some(provider) = sdk.credentials_provider() else {
            report("warning: skipping live Bedrock test: no AWS credential provider");
            return false;
        };
        if let Err(error) = provider.provide_credentials().await {
            report(format!(
                "warning: skipping live Bedrock test: AWS credentials unavailable: {error}"
            ));
            return false;
        }
        assert!(
            sdk.region().is_some(),
            "live Bedrock test has credentials but no AWS region; set a profile region or the authoring configuration's region"
        );
        true
    })
}

Referenced definitions

Input 2: requirements selection requirements.authoring.redaction
:::{req} redaction
Every source text the harness supplies to a model, including mandatory inputs,
`habeas` reads, and `ripgrep` results, and every source text Habeas displays in
the book or `habeas info`, MUST be redacted:

1. In a workspace `habeas.toml` or user configuration file, the value of every
   explicit credential field defined by {cite}`requirements.authoring.credentials`
   MUST be replaced. Such a file that is not valid TOML MUST be replaced whole,
   with `configuration` as the kind, because its fields cannot be located.
2. In every source, each match of a built-in rule of the `secretshape` crate MUST
   be replaced. The replaced region MUST be extended through each adjacent region
   that the crate's entropy heuristic flags and that only whitespace separates
   from the region, repeating until no flagged region is adjacent. The heuristic
   MUST NOT cause redaction on its own.

A replacement MUST read `[REDACTED:<kind>]`, where `<kind>` is the credential
field or the rule's name, and MUST keep every line break within the replaced
text, so line numbers are unchanged. Outlines MUST be built from the original
source, and the structural hash MUST hash each text piece that overlaps a
redacted region in its redacted form, so evidence never depends on a credential's
value and redaction never changes or breaks a file's outline. The `secretshape` version MUST be pinned exactly; upgrading
it MAY change redaction and hashes and MUST be treated as a deliberate change.
:::

Other sources

Input 1: requirements selection requirements.authoring.credentials
:::{req} credentials
Bedrock configurations MAY supply `credentials` containing nonempty
`access_key_id`, `secret_access_key`, and optional nonempty `session_token`.
Ollama and OpenAI configurations MAY supply a nonempty `api_key`. Habeas MUST reject a
Bedrock record combining explicit credentials with `aws_profile`, and an Ollama or OpenAI
record combining `api_key` with `api_key_env`.

Explicit credentials MUST be passed directly to the selected provider without
changing process environment variables or writing credential files. Saved
explicit values MUST round-trip; credentials resolved from profiles or the
environment MUST NOT be serialized back. Debug output, configuration diagnostics,
usage records, and initial prompts MUST NOT include credential values. TOML
diagnostics MUST NOT echo credential-containing source lines. A configuration
file containing explicit credentials MAY be read as source; its credential
values MUST be redacted under {cite}`requirements.authoring.redaction`.
Validation MUST report a workspace `habeas.toml` present in the Git index that
contains explicit credentials, naming the file and the credential fields and
recommending credential-source references, because committed credentials leak.

Documentation MUST discourage literal credentials in workspace files and
recommend AWS profiles or environment-variable references. Examples MUST use
placeholders and explain that workspace files may be committed or read as source
when explicitly allowed.
:::