diff --git a/docs/self-host/knowledge-sources.md b/docs/self-host/knowledge-sources.md index 080199590..8eec105e5 100644 --- a/docs/self-host/knowledge-sources.md +++ b/docs/self-host/knowledge-sources.md @@ -135,6 +135,40 @@ CoderHelm asks for `https://www.googleapis.com/auth/drive.readonly`. A knowledge On a hybrid install that chose CoderHelm's Google app, Drive is offered only while the hosted service has its own Drive app; otherwise the choice is unavailable and the install falls back to its own keys. +## Bedrock knowledge bases, connected in place + +A knowledge base in Amazon Bedrock can be connected in place instead of copied. CoderHelm searches it live in your AWS account each time an agent or the brain chat needs it, and nothing is copied out: no documents, no passages, no vectors. Bedrock turns the question into a search itself, so it doesn't matter which embedding model, chunking or vector store the knowledge base uses. Both kinds of Bedrock knowledge base work, the classic ones whose vector store you run and the managed ones. + +To connect one, open **Knowledge**, **New knowledge base**, **Bedrock knowledge base**. On a self-hosted install the dialog lists the knowledge bases in the install's own account and region; pick one, or paste the ARN of any knowledge base (`arn:aws:bedrock:::knowledge-base/`). Before anything is saved, CoderHelm runs one test search. When it fails, the dialog says why in one sentence and what to do. The base's page then shows **Connected in place: searched live in your AWS account, nothing copied** instead of a list of files, and it takes no uploads or synced apps. + +How it is searched: + +- **Hybrid search.** CoderHelm asks for Bedrock's hybrid search (vectors and keywords) where the vector store supports it, and plain vector search where it doesn't (the test search finds out). No reranking. +- **Merged with your other bases.** Bedrock's ranked list joins the same rank fusion as CoderHelm's own lists, so answers can cite a connected base and an uploaded file side by side. At most three passages come from one document. +- **Citations.** A citation names the document and links to it: the original page for a web, Confluence or SharePoint source, and the S3 console for an S3 object (which opens only for people who can sign in to that account). +- **The region is the ARN's.** A knowledge base in another region than the install is searched in its own region. +- **When it doesn't answer.** The other bases still answer, and the agent or chat is told that this one couldn't be searched, and why. + +### Who searches it + +A knowledge base in the install's own account is searched with the install's own gateway and worker roles. Their read-only policy comes from the same update template as the rest of the install's own-account reads, and for the install it names every knowledge base in its account (`bedrock:Retrieve` and `bedrock:GetDocumentContent` on `arn:aws:bedrock:*::knowledge-base/*`, and `bedrock:ListKnowledgeBases` for the list). Admins still choose which ones a team connects. Each version update brings this policy along. + +A knowledge base in another account is searched with that account's `CoderHelmLogReader` role, the one the account was connected with on **Settings**, **Integrations**, **AWS**. Connect that account first. The role may search only the knowledge bases named in its stack's `KnowledgeBases` parameter (their ARNs separated by commas, or `all` for every knowledge base in that account). When the test search finds the role can't, the dialog says "The role in your account does not allow Retrieve on this knowledge base" and offers a one-click update stack in that account with the parameter filled in. That stack carries everything the role's other update stacks do, so you can delete the older `CoderHelmLogReaderUpdate` stacks once it is in place. If AWS says the role's policies are too large, delete them first. + +### The permissions boundary: one admin step + +Searching needs `bedrock:Retrieve`, and the install's permissions boundary allows it only from this release on. Listing and reading a cited document were already allowed (`bedrock:List*`, `bedrock:Get*`). An update never changes the boundary: the parent stack keeps the boundary installs have, and the new one reaches an install only through the access stack an AWS admin applies (**Settings**, **System**, **Version**, **Permissions**, one link to the AWS console). See [Updates](./updates.md). + +Until an admin applies it, connecting a knowledge base in the install's own account says so plainly: "This install's permission limit doesn't allow searching Bedrock knowledge bases yet: the release that searches them needs a permission change an AWS admin hasn't applied." Nothing else waits on it, and knowledge bases in other accounts work without it. + +### Private networks + +An install whose functions have no internet route needs interface VPC endpoints for `bedrock-agent-runtime` (search) and `bedrock-agent` (the list), in each region a connected knowledge base lives in. Without them the dialog says CoderHelm couldn't reach Bedrock. + +### Who sees what + +Everyone who can read the CoderHelm knowledge base sees what the search returns, whatever their rights in the systems the Bedrock knowledge base was built from. Agents search the bases attached to them, so anyone who can start a run reaches everything the role can search in those bases. Connect only knowledge bases that everyone with that access may read. + ## What runs - **Schedule.** An EventBridge rule (`-knowledge-sync`) drops `knowledge_sync_sweep` on the ticket queue every 15 minutes. The worker queues a sync for each source that is due: every 15 minutes for a Sanity sign-in source, every hour for other sources, or every 6 hours as a backstop for sources that get instant updates. diff --git a/infra/cfn/coderhelm-log-reader-update.yaml b/infra/cfn/coderhelm-log-reader-update.yaml index 149895605..6df4b6e2b 100644 --- a/infra/cfn/coderhelm-log-reader-update.yaml +++ b/infra/cfn/coderhelm-log-reader-update.yaml @@ -1,7 +1,8 @@ AWSTemplateFormatVersion: "2010-09-09" Description: > Brings the existing CoderHelmLogReader role up to date with the read-only - permissions the current CoderHelm release uses. Every permission here is + permissions the current CoderHelm release uses, and lets it search the + Bedrock knowledge bases named in KnowledgeBases. Every permission here is read-only: CoderHelm can list, describe and query, never change anything. It only adds: to drop a permission an older release granted, update the CoderHelmLogReader stack itself with the current role template. @@ -15,6 +16,20 @@ Parameters: Description: The CoderHelm role to update (do not change this value). AllowedPattern: "^CoderHelmLogReader$" + KnowledgeBases: + Type: String + Default: "" + Description: > + Bedrock knowledge bases CoderHelm may search, read-only: their ARNs + separated by commas, or "all" for every knowledge base in this account. + Empty: none (the role reads no knowledge base). + AllowedPattern: "^(|all|arn:aws:bedrock:[a-z0-9-]+:[0-9]{12}:knowledge-base/[A-Z0-9]{10}(,arn:aws:bedrock:[a-z0-9-]+:[0-9]{12}:knowledge-base/[A-Z0-9]{10})*)$" + ConstraintDescription: Knowledge base ARNs separated by commas, "all", or empty. + +Conditions: + ReadsKnowledgeBases: !Not [!Equals [!Ref KnowledgeBases, ""]] + ReadsEveryKnowledgeBase: !Equals [!Ref KnowledgeBases, "all"] + Resources: CoderHelmReadOnlyUpdate: Type: AWS::IAM::Policy @@ -104,3 +119,27 @@ Resources: - "kms:DescribeKey" - "kms:GetKeyPolicy" Resource: "*" + # Bedrock knowledge bases connected in place: searched live in + # this account, nothing copied. Only the knowledge bases named in + # KnowledgeBases (or every one in this account with "all"): + # search and read a cited document, never change one. + - !If + - ReadsKnowledgeBases + - Sid: ReadKnowledgeBases + Effect: Allow + Action: + - "bedrock:Retrieve" + - "bedrock:GetDocumentContent" + Resource: !If + - ReadsEveryKnowledgeBase + - !Sub "arn:aws:bedrock:*:${AWS::AccountId}:knowledge-base/*" + - !Split [",", !Ref KnowledgeBases] + - !Ref AWS::NoValue + - !If + - ReadsEveryKnowledgeBase + - Sid: ListKnowledgeBases + Effect: Allow + Action: + - "bedrock:ListKnowledgeBases" + Resource: "*" + - !Ref AWS::NoValue diff --git a/infra/cfn/coderhelm-log-reader.yaml b/infra/cfn/coderhelm-log-reader.yaml index b59e53495..17636dda2 100644 --- a/infra/cfn/coderhelm-log-reader.yaml +++ b/infra/cfn/coderhelm-log-reader.yaml @@ -1,7 +1,7 @@ AWSTemplateFormatVersion: "2010-09-09" Description: > - Creates a read-only IAM role that allows Coderhelm to query your CloudWatch Logs and metrics - and read Airflow (MWAA) as a Viewer. + Creates a read-only IAM role that allows Coderhelm to query your CloudWatch Logs and metrics, + read Airflow (MWAA) as a Viewer, and search the Bedrock knowledge bases you name. This role uses an External ID to prevent confused deputy attacks. Parameters: @@ -27,6 +27,20 @@ Parameters: allows any role in that account (do not change this value). AllowedPattern: "^[A-Za-z0-9_-]{0,41}$" + KnowledgeBases: + Type: String + Default: "" + Description: > + Bedrock knowledge bases CoderHelm may search, read-only: their ARNs + separated by commas, or "all" for every knowledge base in this account. + Empty: none (the role reads no knowledge base). + AllowedPattern: "^(|all|arn:aws:bedrock:[a-z0-9-]+:[0-9]{12}:knowledge-base/[A-Z0-9]{10}(,arn:aws:bedrock:[a-z0-9-]+:[0-9]{12}:knowledge-base/[A-Z0-9]{10})*)$" + ConstraintDescription: Knowledge base ARNs separated by commas, "all", or empty. + +Conditions: + ReadsKnowledgeBases: !Not [!Equals [!Ref KnowledgeBases, ""]] + ReadsEveryKnowledgeBase: !Equals [!Ref KnowledgeBases, "all"] + Resources: CoderHelmLogReaderRole: Type: AWS::IAM::Role @@ -172,6 +186,34 @@ Resources: - "kms:DescribeKey" - "kms:GetKeyPolicy" Resource: "*" + # Bedrock knowledge bases connected in place: searched live in this + # account, nothing copied. Only the knowledge bases named in + # KnowledgeBases (or every one in this account with "all"): search + # and read a cited document, never change one. + - !If + - ReadsKnowledgeBases + - PolicyName: KnowledgeBasesReadOnly + PolicyDocument: + Version: "2012-10-17" + Statement: + - Sid: ReadKnowledgeBases + Effect: Allow + Action: + - "bedrock:Retrieve" + - "bedrock:GetDocumentContent" + Resource: !If + - ReadsEveryKnowledgeBase + - !Sub "arn:aws:bedrock:*:${AWS::AccountId}:knowledge-base/*" + - !Split [",", !Ref KnowledgeBases] + - !If + - ReadsEveryKnowledgeBase + - Sid: ListKnowledgeBases + Effect: Allow + Action: + - "bedrock:ListKnowledgeBases" + Resource: "*" + - !Ref AWS::NoValue + - !Ref AWS::NoValue Outputs: RoleArn: diff --git a/infra/lib/access.ts b/infra/lib/access.ts index e13d018f9..4d164d8f9 100644 --- a/infra/lib/access.ts +++ b/infra/lib/access.ts @@ -212,6 +212,13 @@ export const BOUNDARY_SERVICES = [ "bedrock:InvokeModelWithResponseStream", "bedrock:Get*", "bedrock:List*", + // Searching a Bedrock knowledge base connected in place, in the install's own + // account (own-account-read.ts; GetDocumentContent and ListKnowledgeBases are + // under Get* and List*). It reaches an install only through the access stack + // an AWS admin applies (native/access-stack.ts): the parent keeps its pinned + // boundary (access-pinned.json), and until the admin step the knowledge base + // page says so (services/common/src/knowledge/remote.rs, refusal). + "bedrock:Retrieve", "cloudformation:*", "cloudfront:*", "cloudwatch:*", diff --git a/infra/lib/own-account-read.ts b/infra/lib/own-account-read.ts index 666af75a7..005eec5e9 100644 --- a/infra/lib/own-account-read.ts +++ b/infra/lib/own-account-read.ts @@ -12,6 +12,13 @@ * Connecting the account still proves the team's own CoderHelmLogReader role * with its private ID (routes/log_analyzer.rs); only reading uses the * install's role (services/common/src/live/aws.rs, install_target). + * + * Bedrock knowledge bases connected in place (services/common/src/knowledge/remote.rs): + * the install is the customer's alone, so its role may search every knowledge + * base in its own account (the template's KnowledgeBases "all"), and list them + * for the picker. Admins still choose which ones a team connects. Retrieve also + * needs the permissions boundary to allow bedrock:Retrieve, which reaches an + * install only through the access stack an AWS admin applies (native/access-stack.ts). */ import * as cdk from "aws-cdk-lib"; import * as iam from "aws-cdk-lib/aws-iam"; @@ -24,15 +31,39 @@ export const OWN_ROLE_ENV = "INSTALL_OWN_ROLE_ARN"; const UPDATE_TEMPLATE = "infra/cfn/coderhelm-log-reader-update.yaml"; const UPDATE_POLICY_ID = "CoderHelmReadOnlyUpdate"; const ROLE_NAME_MARK = "__CODERHELM_ROLE__"; +/** The install's own role searches every knowledge base in its own account. */ +const OWN_KNOWLEDGE_BASES = "all"; +/** The template's conditions for that value. A condition not listed here fails the build. */ +const OWN_CONDITIONS: Record = { ReadsKnowledgeBases: true, ReadsEveryKnowledgeBase: true }; type Statement = { Sid?: string; Effect: string; Action: string | string[]; Resource: unknown }; -/** The update template's statements, as the template has them. */ +/** + * `v` with every `Fn::If` decided by `conditions` and every `AWS::NoValue` + * dropped, as CloudFormation would for those values (CfnInclude keeps them, + * and the policy is written into another stack that has no such conditions). + */ +export function decideConditions(v: unknown, conditions: Record): unknown { + const noValue = (x: unknown) => !!x && typeof x === "object" && (x as any).Ref === "AWS::NoValue"; + if (Array.isArray(v)) return v.map((x) => decideConditions(x, conditions)).filter((x) => !noValue(x)); + if (v && typeof v === "object") { + const o = v as Record; + if (Object.keys(o).length === 1 && Array.isArray(o["Fn::If"])) { + const [name, yes, no] = o["Fn::If"] as [string, unknown, unknown]; + if (!(name in conditions)) throw new Error(`${UPDATE_TEMPLATE}: condition ${name} isn't decided for the install's own role (own-account-read.ts)`); + return decideConditions(conditions[name] ? yes : no, conditions); + } + return Object.fromEntries(Object.entries(o).map(([k, x]) => [k, decideConditions(x, conditions)]).filter(([, x]) => !noValue(x))); + } + return v; +} + +/** The update template's statements for the install's own role: its knowledge bases are every one in its account. */ export function updateTemplateStatements(): Statement[] { const scratch = new cdk.Stack(new cdk.App(), "Scratch"); - const inc = new CfnInclude(scratch, "T", { templateFile: repoPath(UPDATE_TEMPLATE), parameters: { RoleName: ROLE_NAME_MARK } }); + const inc = new CfnInclude(scratch, "T", { templateFile: repoPath(UPDATE_TEMPLATE), parameters: { RoleName: ROLE_NAME_MARK, KnowledgeBases: OWN_KNOWLEDGE_BASES } }); const p = inc.getResource(UPDATE_POLICY_ID) as iam.CfnPolicy; - return scratch.resolve(p.policyDocument).Statement as Statement[]; + return decideConditions(scratch.resolve(p.policyDocument).Statement, OWN_CONDITIONS) as Statement[]; } /** @@ -49,7 +80,7 @@ export function ownAccountStatements(roleArn: string): Statement[] { export function grantOwnAccountRead(scope: Construct, id: string, fn: cdk.aws_lambda.Function): void { const role = fn.role!; new iam.CfnManagedPolicy(scope, id, { - description: "CoderHelm: reads this install's own AWS account (logs, metrics, Airflow, ECS), read-only; kept current by each version update", + description: "CoderHelm: reads this install's own AWS account (logs, metrics, Airflow, ECS, Bedrock knowledge bases), read-only; kept current by each version update", roles: [role.roleName], policyDocument: { Version: "2012-10-17", Statement: ownAccountStatements(role.roleArn) }, }); diff --git a/infra/test/fixtures/native-sim.json b/infra/test/fixtures/native-sim.json index e359b07a5..daafe2ae7 100644 --- a/infra/test/fixtures/native-sim.json +++ b/infra/test/fixtures/native-sim.json @@ -489,6 +489,7 @@ "bedrock:InvokeModelWithResponseStream", "bedrock:Get*", "bedrock:List*", + "bedrock:Retrieve", "cloudformation:*", "cloudfront:*", "cloudwatch:*", @@ -1373,11 +1374,11 @@ {"actions": {"s3:CreateBucket": "allowed", "s3:PutBucketTagging": "allowed"}, "calls": ["AWS::S3::Bucket create"], "context": {"aws:PrincipalArn": "arn:aws:iam::111122223333:role/coderhelm-prod-deploy-stack", "aws:RequestTag/coderhelm:install": "coderhelm-prod", "aws:TagKeys": ["coderhelm:install"]}, "resource": "arn:aws:s3:::coderhelm-prod-release-111122223333"}, {"actions": {"s3:BypassGovernanceRetention": "allowed", "s3:CreateBucketMetadataTableConfiguration": "allowed", "s3:DeleteBucket": "allowed", "s3:DeleteBucketAnalyticsConfiguration": "allowed", "s3:DeleteBucketCors": "allowed", "s3:DeleteBucketEncryption": "allowed", "s3:DeleteBucketLifecycle": "allowed", "s3:DeleteBucketMetadataTableConfiguration": "allowed", "s3:DeleteBucketMetricsConfiguration": "allowed", "s3:DeleteBucketPolicy": "allowed", "s3:DeleteBucketReplication": "allowed", "s3:DeleteBucketTagging": "allowed", "s3:DeleteBucketWebsite": "allowed", "s3:DeleteObject": "allowed", "s3:DeleteObjectVersion": "allowed", "s3:GetAccelerateConfiguration": "allowed", "s3:GetAnalyticsConfiguration": "allowed", "s3:GetBucketAbac": "allowed", "s3:GetBucketAcl": "allowed", "s3:GetBucketCORS": "allowed", "s3:GetBucketDefaultStorageClass": "allowed", "s3:GetBucketLogging": "allowed", "s3:GetBucketMetadataTableConfiguration": "allowed", "s3:GetBucketNotification": "allowed", "s3:GetBucketObjectLockConfiguration": "allowed", "s3:GetBucketOwnershipControls": "allowed", "s3:GetBucketPolicy": "allowed", "s3:GetBucketPublicAccessBlock": "allowed", "s3:GetBucketTagging": "allowed", "s3:GetBucketVersioning": "allowed", "s3:GetBucketWebsite": "allowed", "s3:GetEncryptionConfiguration": "allowed", "s3:GetIntelligentTieringConfiguration": "allowed", "s3:GetInventoryConfiguration": "allowed", "s3:GetLifecycleConfiguration": "allowed", "s3:GetMetricsConfiguration": "allowed", "s3:GetReplicationConfiguration": "allowed", "s3:ListBucket": "allowed", "s3:ListTagsForResource": "allowed", "s3:PutAccelerateConfiguration": "allowed", "s3:PutAnalyticsConfiguration": "allowed", "s3:PutBucketAbac": "allowed", "s3:PutBucketAcl": "allowed", "s3:PutBucketCORS": "allowed", "s3:PutBucketDefaultStorageClass": "allowed", "s3:PutBucketLogging": "allowed", "s3:PutBucketNotification": "allowed", "s3:PutBucketObjectLockConfiguration": "allowed", "s3:PutBucketOwnershipControls": "allowed", "s3:PutBucketPolicy": "allowed", "s3:PutBucketPublicAccessBlock": "allowed", "s3:PutBucketReplication": "allowed", "s3:PutBucketVersioning": "allowed", "s3:PutBucketWebsite": "allowed", "s3:PutEncryptionConfiguration": "allowed", "s3:PutIntelligentTieringConfiguration": "allowed", "s3:PutInventoryConfiguration": "allowed", "s3:PutLifecycleConfiguration": "allowed", "s3:PutMetricsConfiguration": "allowed", "s3:PutObjectLockConfiguration": "allowed", "s3:PutReplicationConfiguration": "allowed", "s3:UntagResource": "allowed", "s3:UpdateBucketMetadataAnnotationTableConfiguration": "allowed", "s3:UpdateBucketMetadataInventoryTableConfiguration": "allowed", "s3:UpdateBucketMetadataJournalTableConfiguration": "allowed"}, "calls": ["AWS::S3::Bucket create", "AWS::S3::Bucket delete", "AWS::S3::Bucket read", "AWS::S3::Bucket tag", "AWS::S3::Bucket update", "AWS::S3::BucketPolicy create", "AWS::S3::BucketPolicy delete", "AWS::S3::BucketPolicy read", "AWS::S3::BucketPolicy update"], "context": {"aws:PrincipalArn": "arn:aws:iam::111122223333:role/coderhelm-prod-deploy-stack", "aws:ResourceTag/coderhelm:install": "coderhelm-prod"}, "resource": "arn:aws:s3:::coderhelm-prod-release-111122223333"}, {"actions": {"s3:CreateBucketMetadataTableConfiguration": "allowed", "s3:PutAccelerateConfiguration": "allowed", "s3:PutAnalyticsConfiguration": "allowed", "s3:PutBucketAbac": "allowed", "s3:PutBucketAcl": "allowed", "s3:PutBucketCORS": "allowed", "s3:PutBucketDefaultStorageClass": "allowed", "s3:PutBucketLogging": "allowed", "s3:PutBucketNotification": "allowed", "s3:PutBucketObjectLockConfiguration": "allowed", "s3:PutBucketOwnershipControls": "allowed", "s3:PutBucketPolicy": "allowed", "s3:PutBucketPublicAccessBlock": "allowed", "s3:PutBucketReplication": "allowed", "s3:PutBucketVersioning": "allowed", "s3:PutBucketWebsite": "allowed", "s3:PutEncryptionConfiguration": "allowed", "s3:PutIntelligentTieringConfiguration": "allowed", "s3:PutInventoryConfiguration": "allowed", "s3:PutLifecycleConfiguration": "allowed", "s3:PutMetricsConfiguration": "allowed", "s3:PutObjectAcl": "allowed", "s3:PutObjectLockConfiguration": "allowed", "s3:PutObjectVersionAcl": "allowed", "s3:PutReplicationConfiguration": "allowed"}, "calls": ["AWS::S3::Bucket create", "AWS::S3::BucketPolicy create"], "context": {"aws:PrincipalArn": "arn:aws:iam::111122223333:role/coderhelm-prod-deploy-stack"}, "resource": "arn:aws:s3:::coderhelm-prod-release-111122223333"}, - {"actions": {"s3:GetObject": "allowed", "s3:GetObjectVersion": "allowed"}, "calls": ["AWS::Lambda::Function create", "AWS::Lambda::Function update"], "context": {"aws:PrincipalArn": "arn:aws:iam::111122223333:role/coderhelm-prod-deploy-stack", "aws:ResourceTag/coderhelm:install": "coderhelm-prod"}, "resource": "arn:aws:s3:::coderhelm-prod-release-111122223333/assets/11f131d7e6e4bcb0bc0bf25345465d4aed0de4295e3f1d4e4b628dcafc64a464.zip"}, {"actions": {"s3:GetObject": "allowed", "s3:GetObjectVersion": "allowed"}, "calls": ["AWS::Lambda::Function create", "AWS::Lambda::Function update"], "context": {"aws:PrincipalArn": "arn:aws:iam::111122223333:role/coderhelm-prod-deploy-stack", "aws:ResourceTag/coderhelm:install": "coderhelm-prod"}, "resource": "arn:aws:s3:::coderhelm-prod-release-111122223333/assets/2819175352ad1ce0dae768e83fc328fb70fb5f10b4a8ff0ccbcb791f02b0716d.zip"}, {"actions": {"s3:GetObject": "allowed", "s3:GetObjectVersion": "allowed"}, "calls": ["AWS::Lambda::Function create", "AWS::Lambda::Function update"], "context": {"aws:PrincipalArn": "arn:aws:iam::111122223333:role/coderhelm-prod-deploy-stack", "aws:ResourceTag/coderhelm:install": "coderhelm-prod"}, "resource": "arn:aws:s3:::coderhelm-prod-release-111122223333/assets/3423a042b818e31c1e34a19d6689ab2e5f9b70fcbe9e71df66f241b20a200bd9.zip"}, {"actions": {"s3:GetObject": "allowed", "s3:GetObjectVersion": "allowed"}, "calls": ["AWS::Lambda::Function create", "AWS::Lambda::Function update"], "context": {"aws:PrincipalArn": "arn:aws:iam::111122223333:role/coderhelm-prod-deploy-stack", "aws:ResourceTag/coderhelm:install": "coderhelm-prod"}, "resource": "arn:aws:s3:::coderhelm-prod-release-111122223333/assets/3c7ee2b1963d304a27fa0796383c8924fe298b4dd2c3730fc94af6b62be134b7.zip"}, {"actions": {"s3:GetObject": "allowed", "s3:GetObjectVersion": "allowed"}, "calls": ["AWS::Lambda::Function create", "AWS::Lambda::Function update"], "context": {"aws:PrincipalArn": "arn:aws:iam::111122223333:role/coderhelm-prod-deploy-stack", "aws:ResourceTag/coderhelm:install": "coderhelm-prod"}, "resource": "arn:aws:s3:::coderhelm-prod-release-111122223333/assets/4a591e9289d3102697d4a891189fc90352ce38222e0b201ae637147e5fd55142.zip"}, + {"actions": {"s3:GetObject": "allowed", "s3:GetObjectVersion": "allowed"}, "calls": ["AWS::Lambda::Function create", "AWS::Lambda::Function update"], "context": {"aws:PrincipalArn": "arn:aws:iam::111122223333:role/coderhelm-prod-deploy-stack", "aws:ResourceTag/coderhelm:install": "coderhelm-prod"}, "resource": "arn:aws:s3:::coderhelm-prod-release-111122223333/assets/9b53b6528f4c8e84d8a67b0bc4e36270272a5e6d8a795aef2c93ec2df25aaa3c.zip"}, {"actions": {"s3:GetObject": "allowed", "s3:GetObjectVersion": "allowed"}, "calls": ["AWS::Lambda::Function create", "AWS::Lambda::Function update"], "context": {"aws:PrincipalArn": "arn:aws:iam::111122223333:role/coderhelm-prod-deploy-stack", "aws:ResourceTag/coderhelm:install": "coderhelm-prod"}, "resource": "arn:aws:s3:::coderhelm-prod-release-111122223333/assets/a77bb41544bf739e532a3faedb5ecda0bba5d9e19ab56eaa0fc6ec92f1bf5827.zip"}, {"actions": {"s3:GetObject": "allowed", "s3:GetObjectVersion": "allowed"}, "calls": ["AWS::Lambda::Function create", "AWS::Lambda::Function update"], "context": {"aws:PrincipalArn": "arn:aws:iam::111122223333:role/coderhelm-prod-deploy-stack", "aws:ResourceTag/coderhelm:install": "coderhelm-prod"}, "resource": "arn:aws:s3:::coderhelm-prod-release-111122223333/assets/ae46d59f832d7b7e8ed231a7a3af7955b7585bf1cef81350968eb356db6a79e0.zip"}, {"actions": {"s3:GetObject": "allowed", "s3:GetObjectVersion": "allowed"}, "calls": ["AWS::Lambda::Function create", "AWS::Lambda::Function update"], "context": {"aws:PrincipalArn": "arn:aws:iam::111122223333:role/coderhelm-prod-deploy-stack", "aws:ResourceTag/coderhelm:install": "coderhelm-prod"}, "resource": "arn:aws:s3:::coderhelm-prod-release-111122223333/assets/bc4e026165204dddfc22a4d9b0dd1cc9b8f53c37b8575a9c4638b289303f2da4.zip"}, @@ -1531,7 +1532,7 @@ ] }, "helper": { - "policy": {"Statement": [{"Action": ["logs:CreateLogStream", "logs:PutLogEvents"], "Effect": "Allow", "Resource": "arn:aws:logs:us-east-1:111122223333:log-group:/aws/lambda/coderhelm-prod-install-helper:*", "Sid": "OwnLog"}, {"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:ListBucket", "s3:ListBucketVersions", "s3:DeleteObjectVersion"], "Effect": "Allow", "Resource": ["arn:aws:s3:::coderhelm-prod-release-111122223333", "arn:aws:s3:::coderhelm-prod-release-111122223333/*"], "Sid": "ReleaseFiles"}, {"Action": ["s3:ListBucket", "s3:ListBucketVersions", "s3:DeleteObject", "s3:DeleteObjectVersion"], "Effect": "Allow", "Resource": ["arn:aws:s3:::coderhelm-prod-*", "arn:aws:s3:::coderhelm-prod-*/*"], "Sid": "EmptyDataBucketsOnDelete"}, {"Action": ["s3:DeleteBucketPolicy", "s3:DeleteBucket", "s3:ListBucket", "s3:ListBucketVersions", "s3:DeleteObject", "s3:DeleteObjectVersion"], "Effect": "Allow", "Resource": ["arn:aws:s3:::coderhelm-setup-0123456789abcdef", "arn:aws:s3:::coderhelm-setup-0123456789abcdef/*"], "Sid": "RetireProgressBucket"}, {"Action": ["secretsmanager:GetSecretValue", "secretsmanager:PutSecretValue", "secretsmanager:DeleteSecret"], "Effect": "Allow", "Resource": "arn:aws:secretsmanager:us-east-1:111122223333:secret:coderhelm/prod/secrets-??????", "Sid": "Secret"}, {"Action": ["dynamodb:BatchWriteItem", "dynamodb:DescribeTable", "dynamodb:DeleteTable", "dynamodb:UpdateTable"], "Effect": "Allow", "Resource": ["arn:aws:dynamodb:us-east-1:111122223333:table/coderhelm-prod", "arn:aws:dynamodb:us-east-1:111122223333:table/coderhelm-prod-*"], "Sid": "AllowlistAndTablesOnDelete"}, {"Action": ["kms:Encrypt", "kms:Decrypt", "kms:GenerateDataKey*", "kms:DescribeKey"], "Condition": {"StringEquals": {"aws:ResourceTag/coderhelm:install": "coderhelm-prod"}}, "Effect": "Allow", "Resource": "*", "Sid": "TableKey"}, {"Action": "lambda:InvokeFunction", "Effect": "Allow", "Resource": "arn:aws:lambda:us-east-1:111122223333:function:coderhelm-prod-updater", "Sid": "Domain"}, {"Action": ["cloudformation:DescribeStacks", "cloudformation:DescribeStackEvents"], "Effect": "Allow", "Resource": "arn:aws:cloudformation:us-east-1:111122223333:stack/coderhelm-prod/*", "Sid": "RootStack"}, {"Action": ["logs:DescribeLogGroups"], "Effect": "Allow", "Resource": "*", "Sid": "LogGroupsOnDelete"}, {"Action": ["logs:DeleteLogGroup", "logs:ListTagsForResource"], "Effect": "Allow", "Resource": ["arn:aws:logs:us-east-1:111122223333:log-group:/aws/lambda/coderhelm-prod-*", "arn:aws:logs:us-east-1:111122223333:log-group:/aws/codebuild/coderhelm-prod-*"], "Sid": "InstallLogGroupsOnDelete"}, {"Action": ["acm:ListCertificates", "acm:ListTagsForCertificate", "acm:DescribeCertificate"], "Condition": {"StringEquals": {"aws:RequestedRegion": "us-east-1"}}, "Effect": "Allow", "Resource": "*", "Sid": "FindCertificates"}, {"Action": "acm:DeleteCertificate", "Condition": {"StringEquals": {"aws:RequestedRegion": "us-east-1", "aws:ResourceTag/coderhelm": "coderhelm-prod"}}, "Effect": "Allow", "Resource": "*", "Sid": "CertificatesOnDelete"}, {"Action": ["ssm:GetParameter", "ssm:DeleteParameter"], "Effect": "Allow", "Resource": "arn:aws:ssm:us-east-1:111122223333:parameter/coderhelm-prod/uninstall/delete-data", "Sid": "UninstallSwitch"}, {"Action": "s3:DeleteBucket", "Effect": "Allow", "Resource": "arn:aws:s3:::coderhelm-prod-data-111122223333", "Sid": "DataBucketOnSwitch"}, {"Action": ["cognito-idp:DescribeUserPool", "cognito-idp:UpdateUserPool", "cognito-idp:DeleteUserPool", "cognito-idp:DeleteUserPoolDomain"], "Condition": {"StringEquals": {"aws:ResourceTag/coderhelm:install": "coderhelm-prod"}}, "Effect": "Allow", "Resource": "arn:aws:cognito-idp:us-east-1:111122223333:userpool/*", "Sid": "UserPoolOnSwitch"}, {"Action": "kms:ListAliases", "Effect": "Allow", "Resource": "*", "Sid": "FindKeyAliases"}, {"Action": "kms:DeleteAlias", "Effect": "Allow", "Resource": "arn:aws:kms:us-east-1:111122223333:alias/coderhelm-prod-*", "Sid": "KeyAliasesOnSwitch"}, {"Action": ["kms:ScheduleKeyDeletion", "kms:DeleteAlias"], "Condition": {"StringEquals": {"aws:ResourceTag/coderhelm:install": "coderhelm-prod"}}, "Effect": "Allow", "Resource": "arn:aws:kms:us-east-1:111122223333:key/*", "Sid": "KeysOnSwitch"}], "Version": "2012-10-17"}, + "policy": {"Statement": [{"Action": ["logs:CreateLogStream", "logs:PutLogEvents"], "Effect": "Allow", "Resource": "arn:aws:logs:us-east-1:111122223333:log-group:/aws/lambda/coderhelm-prod-install-helper:*", "Sid": "OwnLog"}, {"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:ListBucket", "s3:ListBucketVersions", "s3:DeleteObjectVersion"], "Effect": "Allow", "Resource": ["arn:aws:s3:::coderhelm-prod-release-111122223333", "arn:aws:s3:::coderhelm-prod-release-111122223333/*"], "Sid": "ReleaseFiles"}, {"Action": ["s3:ListBucket", "s3:ListBucketVersions", "s3:DeleteObject", "s3:DeleteObjectVersion"], "Effect": "Allow", "Resource": ["arn:aws:s3:::coderhelm-prod-*", "arn:aws:s3:::coderhelm-prod-*/*"], "Sid": "EmptyDataBucketsOnDelete"}, {"Action": ["s3:DeleteBucketPolicy", "s3:DeleteBucket", "s3:ListBucket", "s3:ListBucketVersions", "s3:DeleteObject", "s3:DeleteObjectVersion"], "Effect": "Allow", "Resource": ["arn:aws:s3:::coderhelm-setup-0123456789abcdef", "arn:aws:s3:::coderhelm-setup-0123456789abcdef/*"], "Sid": "RetireProgressBucket"}, {"Action": ["secretsmanager:GetSecretValue", "secretsmanager:PutSecretValue", "secretsmanager:DeleteSecret"], "Effect": "Allow", "Resource": "arn:aws:secretsmanager:us-east-1:111122223333:secret:coderhelm/prod/secrets-??????", "Sid": "Secret"}, {"Action": ["dynamodb:BatchWriteItem", "dynamodb:DescribeTable", "dynamodb:DeleteTable", "dynamodb:UpdateTable"], "Effect": "Allow", "Resource": ["arn:aws:dynamodb:us-east-1:111122223333:table/coderhelm-prod", "arn:aws:dynamodb:us-east-1:111122223333:table/coderhelm-prod-*"], "Sid": "AllowlistAndTablesOnDelete"}, {"Action": ["kms:Encrypt", "kms:Decrypt", "kms:GenerateDataKey*", "kms:DescribeKey"], "Condition": {"StringEquals": {"aws:ResourceTag/coderhelm:install": "coderhelm-prod"}}, "Effect": "Allow", "Resource": "*", "Sid": "TableKey"}, {"Action": "lambda:InvokeFunction", "Effect": "Allow", "Resource": "arn:aws:lambda:us-east-1:111122223333:function:coderhelm-prod-updater", "Sid": "Domain"}, {"Action": ["cloudformation:DescribeStacks", "cloudformation:DescribeStackEvents"], "Effect": "Allow", "Resource": "arn:aws:cloudformation:us-east-1:111122223333:stack/coderhelm-prod/*", "Sid": "RootStack"}, {"Action": "cloudformation:GetTemplate", "Effect": "Allow", "Resource": "arn:aws:cloudformation:us-east-1:111122223333:stack/coderhelm-prod/*", "Sid": "RootStackTemplate"}, {"Action": ["logs:DescribeLogGroups"], "Effect": "Allow", "Resource": "*", "Sid": "LogGroupsOnDelete"}, {"Action": ["logs:DeleteLogGroup", "logs:ListTagsForResource"], "Effect": "Allow", "Resource": ["arn:aws:logs:us-east-1:111122223333:log-group:/aws/lambda/coderhelm-prod-*", "arn:aws:logs:us-east-1:111122223333:log-group:/aws/codebuild/coderhelm-prod-*"], "Sid": "InstallLogGroupsOnDelete"}, {"Action": ["acm:ListCertificates", "acm:ListTagsForCertificate", "acm:DescribeCertificate"], "Condition": {"StringEquals": {"aws:RequestedRegion": "us-east-1"}}, "Effect": "Allow", "Resource": "*", "Sid": "FindCertificates"}, {"Action": "acm:DeleteCertificate", "Condition": {"StringEquals": {"aws:RequestedRegion": "us-east-1", "aws:ResourceTag/coderhelm": "coderhelm-prod"}}, "Effect": "Allow", "Resource": "*", "Sid": "CertificatesOnDelete"}, {"Action": ["ssm:GetParameter", "ssm:DeleteParameter"], "Effect": "Allow", "Resource": "arn:aws:ssm:us-east-1:111122223333:parameter/coderhelm-prod/uninstall/delete-data", "Sid": "UninstallSwitch"}, {"Action": "s3:DeleteBucket", "Effect": "Allow", "Resource": "arn:aws:s3:::coderhelm-prod-data-111122223333", "Sid": "DataBucketOnSwitch"}, {"Action": ["cognito-idp:DescribeUserPool", "cognito-idp:UpdateUserPool", "cognito-idp:DeleteUserPool", "cognito-idp:DeleteUserPoolDomain"], "Condition": {"StringEquals": {"aws:ResourceTag/coderhelm:install": "coderhelm-prod"}}, "Effect": "Allow", "Resource": "arn:aws:cognito-idp:us-east-1:111122223333:userpool/*", "Sid": "UserPoolOnSwitch"}, {"Action": "kms:ListAliases", "Effect": "Allow", "Resource": "*", "Sid": "FindKeyAliases"}, {"Action": "kms:DeleteAlias", "Effect": "Allow", "Resource": "arn:aws:kms:us-east-1:111122223333:alias/coderhelm-prod-*", "Sid": "KeyAliasesOnSwitch"}, {"Action": ["kms:ScheduleKeyDeletion", "kms:DeleteAlias"], "Condition": {"StringEquals": {"aws:ResourceTag/coderhelm:install": "coderhelm-prod"}}, "Effect": "Allow", "Resource": "arn:aws:kms:us-east-1:111122223333:key/*", "Sid": "KeysOnSwitch"}], "Version": "2012-10-17"}, "rows": [ {"action": "s3:PutObject", "resource": "arn:aws:s3:::coderhelm-prod-release-111122223333/assets/a.zip", "simulator": "allowed", "want": "allowed"}, {"action": "s3:DeleteObject", "resource": "arn:aws:s3:::coderhelm-prod-release-111122223333/assets/a.zip", "simulator": "allowed", "want": "allowed"}, diff --git a/infra/test/native-access.test.ts b/infra/test/native-access.test.ts index 4f3b73dda..ad2cf93c0 100644 --- a/infra/test/native-access.test.ts +++ b/infra/test/native-access.test.ts @@ -52,14 +52,16 @@ const canon = (v: unknown) => JSON.stringify(v, (_k, x) => (x && typeof x === "o const sha = (v: unknown) => crypto.createHash("sha256").update(canon(v)).digest("hex"); /** - * Today's boundary and deploy role policy, as their sha256. A change here + * Today's boundary and deploy role policy, as their sha256. Last changed for + * bedrock:Retrieve (a Bedrock knowledge base connected in place, searched with + * the install's own role). A change here * reaches no install by itself: an AWS admin applies it through the access * stack (Settings, System, Permissions). Before changing these two values, * batch it with whatever else needs the same admin step, and say so in the * release notes; the dashboard then offers it as one optional item. */ const ACCESS_DOCS = { - boundary: "e336aa5d3446090ae84ae7b36ab55953455d662b997ab0947aabb5a091ec555e", + boundary: "1dfff5e344b055bba2eb45e611d86466018eff191525cbbffab7fdf33b841141", deployRole: "d11f40637e639812ba5408d153351341bc593cb604726f6cb4193861c2dd7b1f", }; @@ -158,3 +160,19 @@ test("the access stack has no service role and changes nothing on delete", () => for (const r of Object.values(ACCESS.Resources)) assert.equal(r.DeletionPolicy, undefined); assert.match(fs.readFileSync(path.join(__dirname, "..", "..", "..", "lambda", "native-access", "handler.py"), "utf8"), /On Delete it changes nothing/); }); + +test("searching a connected Bedrock knowledge base arrives with the access stack, never with an update", () => { + const values = prodValues("111122223333", "us-east-1"); + const kb = { action: "bedrock:Retrieve", resource: "arn:aws:bedrock:us-east-1:111122223333:knowledge-base/ABCDE12345" }; + const anything: PolicyDocument = { Version: "2012-10-17", Statement: [{ Sid: "All", Effect: "Allow", Action: "*", Resource: "*" }] }; + // The parent's boundary is the pinned one: an update leaves an install without Retrieve. + const pinned = resolveValue((pinnedAccess().Boundary as any).Properties.PolicyDocument, { values, conditions: { HasEmailFrom: true } }) as PolicyDocument; + assert.notEqual(decision([anything], pinned, kb), "allowed", "the pinned boundary must not change"); + // Today's boundary, which access.json writes when an AWS admin applies it, allows it. + const today = resolveValue(ACCESS.Resources.Access.Properties.Boundary.Document, { values: { ...values, EmailFrom: "owner@example.org" }, conditions: { HasEmailFrom: true } }) as PolicyDocument; + assert.equal(decision([anything], today, kb), "allowed"); + // Listing and reading a cited document were already allowed (bedrock:List*, bedrock:Get*). + for (const action of ["bedrock:ListKnowledgeBases", "bedrock:GetDocumentContent"]) { + assert.equal(decision([anything], pinned, { ...kb, action }), "allowed", action); + } +}); diff --git a/infra/test/synth.test.ts b/infra/test/synth.test.ts index 3ca8c59fb..ab172e7dd 100644 --- a/infra/test/synth.test.ts +++ b/infra/test/synth.test.ts @@ -195,7 +195,7 @@ test("self-host: the gateway and worker read the install's own account with this for (const a of needed) assert.ok(doc.includes(`"${a}"`), `${fn} lacks ${a}`); // Only reads: list, describe, get, query, never a write. const actions: string[] = policies[0].Properties.PolicyDocument.Statement.flatMap((s: any) => ([] as string[]).concat(s.Action)); - for (const a of actions) assert.match(a, /^[a-z0-9-]+:(List|Describe|Get|Filter|Start(Query)?$|Stop(Query)?$|BatchGet|Simulate|InvokeRestApi)/, a); + for (const a of actions) assert.match(a, /^[a-z0-9-]+:(List|Describe|Get|Filter|Start(Query)?$|Stop(Query)?$|BatchGet|Simulate|InvokeRestApi|Retrieve$)/, a); // It checks its own permissions on its own role only. const sim = policies[0].Properties.PolicyDocument.Statement.find((s: any) => ([] as string[]).concat(s.Action).includes("iam:SimulatePrincipalPolicy")); assert.ok(JSON.stringify(sim.Resource).includes("Fn::GetAtt"), "its own role's ARN"); diff --git a/services/Cargo.lock b/services/Cargo.lock index aabab29fd..d1645ee45 100644 --- a/services/Cargo.lock +++ b/services/Cargo.lock @@ -239,6 +239,55 @@ dependencies = [ "uuid", ] +[[package]] +name = "aws-sdk-bedrockagent" +version = "1.129.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c012c3bcf5d19e7591b881bd7996aa5ff0163b07aeefca49b1b4ebabcadfc12e" +dependencies = [ + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-observability", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "http 0.2.12", + "http 1.4.0", + "regex-lite", + "tracing", +] + +[[package]] +name = "aws-sdk-bedrockagentruntime" +version = "1.125.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c2c4a870cd06e0daa3eab787a0da73ffa505861a688db665b589da55cfce2a9" +dependencies = [ + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-eventstream", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-observability", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "http 0.2.12", + "http 1.4.0", + "regex-lite", + "tracing", +] + [[package]] name = "aws-sdk-bedrockruntime" version = "1.129.0" @@ -1440,6 +1489,8 @@ version = "0.1.0" dependencies = [ "async-trait", "aws-config", + "aws-sdk-bedrockagent", + "aws-sdk-bedrockagentruntime", "aws-sdk-bedrockruntime", "aws-sdk-cloudformation", "aws-sdk-cloudwatch", diff --git a/services/common/Cargo.toml b/services/common/Cargo.toml index 353564646..e706389ef 100644 --- a/services/common/Cargo.toml +++ b/services/common/Cargo.toml @@ -28,6 +28,10 @@ aws-sdk-scheduler = "1" hex = "0.4" # embed: Titan embeddings on CoderHelm's own AWS account, metered aws-sdk-bedrockruntime = "1" +# knowledge: a Bedrock knowledge base connected in place, searched live in +# the team's own account (Retrieve), and listed on a self-hosted install +aws-sdk-bedrockagentruntime = "1" +aws-sdk-bedrockagent = "1" tokio = { version = "1", features = ["macros", "time", "net", "rt", "sync"] } # live: read-only lookups against a team's own systems graphql-parser = "0.4" diff --git a/services/common/src/knowledge/mod.rs b/services/common/src/knowledge/mod.rs index 1b8474041..b118a75c1 100644 --- a/services/common/src/knowledge/mod.rs +++ b/services/common/src/knowledge/mod.rs @@ -16,10 +16,17 @@ //! the old one only once it is ready. Search loads the indexes of the bases //! asked for (cached per version) and ranks passages in memory, which is //! comfortably fast at the limits below. +//! +//! A base can instead be **connected in place** ([`Backend::Remote`]): an +//! Amazon Bedrock knowledge base in the team's own AWS account, searched +//! live where it is ([`remote`]). Nothing of it is copied: it has no files, +//! no passages and no vectors here, and search merges the list Bedrock +//! ranked with the local ones. pub mod answer; pub mod chunk; pub mod extract; +pub mod remote; pub mod search; pub mod sources; @@ -88,6 +95,117 @@ pub struct Base { pub created_by: String, #[serde(default)] pub updated_at: String, + /// Where its passages are: here ([`Backend::Local`], every base made + /// before connecting in place existed), or searched live elsewhere. + #[serde(default, skip_serializing_if = "Backend::is_local")] + pub backend: Backend, +} + +/// Where a base's passages live and are ranked. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Backend { + /// Uploaded and synced files, embedded and ranked by Coderhelm. + #[default] + Local, + /// Searched live where it lives; nothing is copied. + Remote(Remote), +} + +impl Backend { + pub fn is_local(&self) -> bool { + matches!(self, Backend::Local) + } +} + +/// A knowledge base connected in place. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Remote { + pub provider: Provider, + /// The provider's address for it (a Bedrock knowledge base's ARN). + pub target: String, + /// The region it lives in, read from the ARN (never the install's). + pub region: String, + /// How Coderhelm reaches it. + pub access: Access, + /// Bedrock's hybrid search (vectors and keywords) is used: true unless + /// the knowledge base's vector store refused it when it was connected. + #[serde(default = "yes")] + pub hybrid: bool, +} + +fn yes() -> bool { + true +} + +/// Who answers for a connected knowledge base. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Provider { + /// Amazon Bedrock Knowledge Bases (`bedrock-agent-runtime` Retrieve). + BedrockKb, +} + +impl Provider { + pub fn label(self) -> &'static str { + match self { + Provider::BedrockKb => "Bedrock knowledge base", + } + } +} + +/// The AWS identity a connected knowledge base is searched with. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Access { + /// A self-hosted install's own role, in the install's own account + /// (`live::aws::install_read_role`): its permissions come with each + /// version update. + Install, + /// The team's connected `CoderHelmLogReader` role in `account`, taken + /// on with the team's private ID for a 15 minute session + /// (`live::aws::assume`). The private ID is read from Coderhelm's own + /// record of the account, never stored here. + Account { account: String }, +} + +/// Where a passage came from, as a [`search::Hit`] and a citation name it +/// (`source_kind`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SourceKind { + /// A file someone uploaded. + Upload, + /// An item synced from a connected app. + Synced(sources::Kind), + /// A passage a connected Bedrock knowledge base returned, live. + BedrockKb, +} + +impl SourceKind { + /// The key a hit and a citation carry (empty for an upload). + pub fn key(self) -> &'static str { + match self { + SourceKind::Upload => "", + SourceKind::Synced(k) => k.key(), + SourceKind::BedrockKb => "bedrock_kb", + } + } + + pub fn label(self) -> &'static str { + match self { + SourceKind::Upload => "Uploaded file", + SourceKind::Synced(k) => k.label(), + SourceKind::BedrockKb => Provider::BedrockKb.label(), + } + } + + pub fn parse(key: &str) -> Option { + match key { + "" => Some(SourceKind::Upload), + "bedrock_kb" => Some(SourceKind::BedrockKb), + k => sources::Kind::parse(k).map(SourceKind::Synced), + } + } } fn default_read_role() -> String { @@ -95,6 +213,14 @@ fn default_read_role() -> String { } impl Base { + /// Connected in place: searched live where it lives, nothing copied. + pub fn remote(&self) -> Option<&Remote> { + match &self.backend { + Backend::Remote(r) => Some(r), + Backend::Local => None, + } + } + /// May someone with `role` read this base? pub fn readable_by(&self, role: &str) -> bool { role_level(role) >= role_level(&self.read_role) @@ -438,6 +564,53 @@ mod tests { assert_eq!(read_data::(&base_record("t", &b)).unwrap(), b); } + #[test] + fn every_existing_base_is_local_and_a_connected_one_round_trips() { + // A record saved before backends existed reads as local, and a local + // base is saved exactly as before (no new field). + let old: Base = serde_json::from_str(r#"{"id":"k","name":"n"}"#).unwrap(); + assert_eq!(old.backend, Backend::Local); + assert!(old.remote().is_none()); + let saved = serde_json::to_value(&old).unwrap(); + assert!(saved.get("backend").is_none(), "{saved}"); + let b = Base { + id: "kb".into(), + name: "Runbooks".into(), + backend: Backend::Remote(Remote { + provider: Provider::BedrockKb, + target: "arn:aws:bedrock:eu-west-1:111122223333:knowledge-base/ABCDE12345".into(), + region: "eu-west-1".into(), + access: Access::Account { + account: "111122223333".into(), + }, + hybrid: true, + }), + ..Default::default() + }; + let v = serde_json::to_value(&b).unwrap(); + assert_eq!(v["backend"]["kind"], "remote"); + assert_eq!(v["backend"]["provider"], "bedrock_kb"); + assert_eq!(v["backend"]["access"]["kind"], "account"); + assert_eq!(read_data::(&base_record("t", &b)).unwrap(), b); + // No private ID is ever kept on the base. + assert!(!v.to_string().contains("external")); + let install: Access = serde_json::from_str(r#"{"kind":"install"}"#).unwrap(); + assert_eq!(install, Access::Install); + } + + #[test] + fn source_kinds_name_where_a_passage_came_from() { + assert_eq!(SourceKind::BedrockKb.key(), "bedrock_kb"); + assert_eq!(SourceKind::BedrockKb.label(), "Bedrock knowledge base"); + assert_eq!(SourceKind::parse("bedrock_kb"), Some(SourceKind::BedrockKb)); + assert_eq!( + SourceKind::parse("notion"), + Some(SourceKind::Synced(sources::Kind::Notion)) + ); + assert_eq!(SourceKind::parse(""), Some(SourceKind::Upload)); + assert_eq!(SourceKind::parse("nope"), None); + } + #[test] fn only_a_ready_version_is_searched() { let mut f = FileMeta { diff --git a/services/common/src/knowledge/remote.rs b/services/common/src/knowledge/remote.rs new file mode 100644 index 000000000..67c60f679 --- /dev/null +++ b/services/common/src/knowledge/remote.rs @@ -0,0 +1,978 @@ +//! Knowledge bases connected in place: an Amazon Bedrock knowledge base in +//! the team's own AWS account, searched live with `bedrock-agent-runtime` +//! Retrieve. Nothing is copied: Bedrock embeds the question and ranks its +//! own passages, and [`super::search::search`] merges that ranked list with +//! the local ones. +//! +//! Who calls Retrieve: +//! +//! - **Hosted**: a 15 minute session on the team's `CoderHelmLogReader` role +//! in the knowledge base's account, taken on with the team's private ID +//! ([`crate::live::aws::assume`]). The role's `ReadKnowledgeBases` +//! statement (both log reader templates) names the knowledge bases it may +//! search. A Bedrock resource policy naming Coderhelm's shared role is +//! never used: any team that learned the ARN could search through it. +//! - **Self-hosted**, a knowledge base in the install's own account: the +//! install's own role ([`crate::live::aws::own_session`]), whose +//! permissions arrive with each version update. Its permissions boundary +//! must allow `bedrock:Retrieve`, which comes with the access stack an AWS +//! admin applies; until then AWS says the boundary refused, and that is +//! said plainly ([`refusal`]). +//! +//! Search is HYBRID (vectors and keywords) where the vector store supports +//! it, with no reranking. The region is always the ARN's. + +use serde::Serialize; +use serde_json::Value; + +use super::search::{Hit, Retriever}; +use super::{Access, Backend, Base, Provider, Remote}; +use crate::live::aws::{self, Session}; +use crate::live::aws_account::{self, AwsAccount}; + +// ── The ARN ────────────────────────────────────────────────────────────────── + +/// A Bedrock knowledge base's ARN, read apart. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KbArn { + pub region: String, + pub account: String, + /// The ten character id. + pub id: String, +} + +impl KbArn { + pub fn arn(&self) -> String { + format!( + "arn:aws:bedrock:{}:{}:knowledge-base/{}", + self.region, self.account, self.id + ) + } +} + +fn is_region(r: &str) -> bool { + let parts: Vec<&str> = r.split('-').collect(); + parts.len() >= 3 + && parts.iter().all(|p| { + !p.is_empty() + && p.chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()) + }) + && parts + .last() + .is_some_and(|p| p.chars().all(|c| c.is_ascii_digit())) +} + +/// `arn:aws:bedrock:::knowledge-base/`, or what is +/// wrong with it in plain words. +pub fn parse_kb_arn(raw: &str) -> Result { + let raw = raw.trim(); + let fix = "Paste the knowledge base's ARN from the Bedrock console. It looks like arn:aws:bedrock:us-east-1:111122223333:knowledge-base/ABCDE12345."; + let parts: Vec<&str> = raw.splitn(6, ':').collect(); + let [p, partition, svc, region, account, resource] = parts.as_slice() else { + return Err(format!("That isn't a knowledge base ARN. {fix}")); + }; + let id = resource.strip_prefix("knowledge-base/").unwrap_or(""); + let ok = *p == "arn" + && *partition == "aws" + && *svc == "bedrock" + && is_region(region) + && account.len() == 12 + && account.chars().all(|c| c.is_ascii_digit()) + && id.len() == 10 + && id + .chars() + .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit()); + if !ok { + return Err(format!("That isn't a knowledge base ARN. {fix}")); + } + Ok(KbArn { + region: region.to_string(), + account: account.to_string(), + id: id.to_string(), + }) +} + +// ── Failures, in plain words ───────────────────────────────────────────────── + +/// Why a connected knowledge base couldn't be searched, and what to do. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Refusal { + /// `access`, `boundary`, `resource_policy`, `scp`, `not_found`, + /// `invalid`, `busy`, `store`, `account`, `reach` or `other`. + pub code: &'static str, + pub message: String, + pub fix: String, +} + +impl Refusal { + fn new(code: &'static str, message: impl Into, fix: impl Into) -> Refusal { + Refusal { + code, + message: message.into(), + fix: fix.into(), + } + } +} + +impl std::fmt::Display for Refusal { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{} {}", self.message, self.fix) + } +} + +/// The message of the plain "the role may not" refusal. +pub const NOT_ALLOWED: &str = + "The role in your account does not allow Retrieve on this knowledge base."; + +/// Bedrock's error `code` and `message` for a Retrieve, in plain words. +pub fn refusal(code: &str, message: &str) -> Refusal { + let lower = message.to_ascii_lowercase(); + let detail = crate::live::error_detail(code, message); + match code { + "AccessDeniedException" | "AccessDenied" | "UnauthorizedException" => { + if crate::live::boundary_refusal(message) { + Refusal::new( + "boundary", + "This install's permission limit doesn't allow searching Bedrock knowledge bases yet: the release that searches them needs a permission change an AWS admin hasn't applied.", + crate::live::PENDING_PERMISSION_FIX, + ) + } else if lower.contains("service control policy") { + Refusal::new( + "scp", + "An organization policy (SCP) blocks Retrieve on this knowledge base.", + "Ask your AWS organization's admin to allow bedrock:Retrieve for this role, then try again.", + ) + } else if lower.contains("resource-based policy") || lower.contains("resource policy") { + Refusal::new( + "resource_policy", + "The knowledge base's resource policy doesn't allow the role Coderhelm uses.", + "Add a statement to the knowledge base's resource policy that allows bedrock:Retrieve and bedrock:GetDocumentContent for that role on this knowledge base's ARN, then try again.", + ) + } else { + Refusal::new( + "access", + NOT_ALLOWED, + "Give the role bedrock:Retrieve and bedrock:GetDocumentContent on this knowledge base (the CoderHelmLogReader update does it), then try again.", + ) + } + } + "ResourceNotFoundException" => Refusal::new( + "not_found", + "Bedrock has no knowledge base with that ARN.", + "Check the ARN: copy it from the knowledge base's page in the Bedrock console. Its region and account are part of it.", + ), + "ValidationException" => Refusal::new( + "invalid", + format!("Bedrock refused the search ({detail})."), + "Check that the knowledge base's status is Available and its data source has synced at least once.", + ), + "ThrottlingException" | "ServiceQuotaExceededException" => Refusal::new( + "busy", + "Bedrock is limiting searches on this knowledge base right now.", + "Try again in a minute.", + ), + "DependencyFailedException" | "BadGatewayException" => Refusal::new( + "store", + format!("The vector store behind the knowledge base didn't answer Bedrock ({detail})."), + "Check the vector store behind the knowledge base in your AWS account, then try again.", + ), + "" => Refusal::new( + "reach", + format!("Coderhelm couldn't reach Bedrock ({detail})."), + "Try again. An install in a private network needs a VPC endpoint for bedrock-agent-runtime in the knowledge base's region.", + ), + _ => Refusal::new( + "other", + format!("Bedrock couldn't search the knowledge base ({detail})."), + "Try again. If it keeps failing, check the knowledge base in the Bedrock console.", + ), + } +} + +// ── Who searches it ────────────────────────────────────────────────────────── + +/// How a knowledge base at `arn` is reached: with the install's own role +/// when it is in the self-hosted install's own account, otherwise with the +/// team's connected log reader role in that account. +pub fn access_for( + arn: &KbArn, + own_role: Option<&str>, + accounts: &[AwsAccount], +) -> Result { + let own_account = own_role + .and_then(|r| r.split(':').nth(4)) + .filter(|a| a.len() == 12); + if own_account == Some(arn.account.as_str()) { + return Ok(Access::Install); + } + if accounts.iter().any(|a| a.account == arn.account) { + return Ok(Access::Account { + account: arn.account.clone(), + }); + } + Err(Refusal::new( + "account", + format!( + "AWS account {} isn't connected to Coderhelm.", + arn.account + ), + "Connect it first on Settings, Integrations, AWS (it creates the read-only CoderHelmLogReader role), then paste the ARN again.", + )) +} + +/// A connected Bedrock knowledge base for `arn`, reached with `access`. +pub fn bedrock_remote(arn: &KbArn, access: Access, hybrid: bool) -> Remote { + Remote { + provider: Provider::BedrockKb, + target: arn.arn(), + region: arn.region.clone(), + access, + hybrid, + } +} + +/// Takes on the identity `remote` is searched with, for `team_id`. The +/// team's private ID comes from Coderhelm's own record of the account. +pub async fn session( + sts: &aws_sdk_sts::Client, + dynamo: &aws_sdk_dynamodb::Client, + accounts_table: &str, + team_id: &str, + remote: &Remote, + actor: &str, +) -> Result { + match &remote.access { + Access::Install => { + if aws::install_read_role().is_none() { + return Err(Refusal::new( + "account", + "This Coderhelm doesn't have an install role to search with.", + "Connect the knowledge base's AWS account on Settings, Integrations, AWS, then connect the knowledge base again.", + )); + } + aws::own_session(&remote.region).ok_or_else(|| { + Refusal::new( + "reach", + "This install's own AWS credentials aren't available here.", + "Try again in a minute.", + ) + }) + } + Access::Account { account } => { + let accounts = if accounts_table.is_empty() { + Vec::new() + } else { + aws_account::list(dynamo, accounts_table, team_id) + .await + .map_err(|e| { + tracing::warn!(error = %e, "Could not read AWS accounts"); + Refusal::new( + "reach", + "Coderhelm couldn't read your connected AWS accounts.", + "Try again in a minute.", + ) + })? + }; + let Some(a) = accounts.iter().find(|a| &a.account == account) else { + return Err(Refusal::new( + "account", + format!("AWS account {account} isn't connected to Coderhelm any more."), + "Connect it again on Settings, Integrations, AWS.", + )); + }; + let target = aws::AwsTarget { + region: remote.region.clone(), + ..a.target() + }; + aws::assume(sts, &target, actor) + .await + .map_err(|e| Refusal::new("access", e.message, e.fix)) + } + } +} + +// ── Retrieve ───────────────────────────────────────────────────────────────── + +/// One passage as Bedrock returned it. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Passage { + pub text: String, + /// `S3`, `WEB`, `CONFLUENCE`, `SHAREPOINT`, `SALESFORCE`, `CUSTOM`, ... + pub location_type: String, + /// The location's URI, URL or id. + pub location: String, + pub metadata: serde_json::Map, + pub score: f64, +} + +fn runtime_client(s: &Session, region: &str) -> aws_sdk_bedrockagentruntime::Client { + use aws_sdk_bedrockagentruntime::config::{BehaviorVersion, Credentials, Region}; + let creds = Credentials::new( + &s.access_key_id, + &s.secret_access_key, + Some(s.session_token.clone()), + None, + "coderhelm-team-role", + ); + aws_sdk_bedrockagentruntime::Client::from_conf( + aws_sdk_bedrockagentruntime::Config::builder() + .behavior_version(BehaviorVersion::latest()) + .region(Region::new(region.to_string())) + .credentials_provider(creds) + .build(), + ) +} + +fn document_json(d: &aws_smithy_types::Document) -> Value { + use aws_smithy_types::{Document, Number}; + match d { + Document::Object(m) => Value::Object( + m.iter() + .map(|(k, v)| (k.clone(), document_json(v))) + .collect(), + ), + Document::Array(a) => Value::Array(a.iter().map(document_json).collect()), + Document::Number(Number::PosInt(n)) => Value::from(*n), + Document::Number(Number::NegInt(n)) => Value::from(*n), + Document::Number(Number::Float(f)) => Value::from(*f), + Document::String(s) => Value::String(s.clone()), + Document::Bool(b) => Value::Bool(*b), + Document::Null => Value::Null, + } +} + +fn passage_of(r: &aws_sdk_bedrockagentruntime::types::KnowledgeBaseRetrievalResult) -> Passage { + let (location_type, location) = r + .location() + .map(|l| { + let at = l + .s3_location() + .and_then(|x| x.uri()) + .or_else(|| l.web_location().and_then(|x| x.url())) + .or_else(|| l.confluence_location().and_then(|x| x.url())) + .or_else(|| l.share_point_location().and_then(|x| x.url())) + .or_else(|| l.salesforce_location().and_then(|x| x.url())) + .or_else(|| l.kendra_document_location().and_then(|x| x.uri())) + .or_else(|| l.custom_document_location().and_then(|x| x.id())) + .unwrap_or(""); + (l.r#type().as_str().to_string(), at.to_string()) + }) + .unwrap_or_default(); + Passage { + text: r + .content() + .map(|c| c.text().to_string()) + .unwrap_or_default(), + location_type, + location, + metadata: r + .metadata() + .map(|m| { + m.iter() + .map(|(k, v)| (k.clone(), document_json(v))) + .collect() + }) + .unwrap_or_default(), + score: r.score().unwrap_or(0.0), + } +} + +/// One Retrieve: up to `k` passages, HYBRID when `hybrid`, no reranking. +pub async fn retrieve_with( + s: &Session, + remote: &Remote, + query: &str, + k: usize, + hybrid: bool, +) -> Result, Refusal> { + use aws_sdk_bedrockagentruntime::error::ProvideErrorMetadata; + use aws_sdk_bedrockagentruntime::types::{ + KnowledgeBaseQuery, KnowledgeBaseRetrievalConfiguration, + KnowledgeBaseVectorSearchConfiguration, SearchType, + }; + let mut search = + KnowledgeBaseVectorSearchConfiguration::builder().number_of_results(k.clamp(1, 100) as i32); + if hybrid { + search = search.override_search_type(SearchType::Hybrid); + } + let out = runtime_client(s, &remote.region) + .retrieve() + .knowledge_base_id(&remote.target) + .retrieval_query( + KnowledgeBaseQuery::builder() + .text(crate::truncate_str(query, 1_000)) + .build(), + ) + .retrieval_configuration( + KnowledgeBaseRetrievalConfiguration::builder() + .vector_search_configuration(search.build()) + .build(), + ) + .send() + .await + .map_err(|e| match e.as_service_error() { + Some(se) => refusal(se.code().unwrap_or("Unknown"), se.message().unwrap_or("")), + None => refusal( + "", + &aws_sdk_bedrockagentruntime::error::DisplayErrorContext(&e).to_string(), + ), + })?; + Ok(out.retrieval_results().iter().map(passage_of).collect()) +} + +/// Bedrock refused HYBRID because the vector store can't do it (S3 +/// Vectors, Pinecone and others search by vector only). +fn hybrid_unsupported(r: &Refusal) -> bool { + let m = r.message.to_ascii_lowercase(); + r.code == "invalid" + && (m.contains("hybrid") || m.contains("search type") || m.contains("overridesearchtype")) +} + +/// The test search run when a knowledge base is connected: `Ok(hybrid)` +/// says whether HYBRID works there (when the store refuses it, plain vector +/// search is tried and used instead). +pub async fn test_retrieve(s: &Session, remote: &Remote) -> Result { + let probe = "Coderhelm connection check"; + match retrieve_with(s, remote, probe, 1, true).await { + Ok(_) => Ok(true), + Err(r) if hybrid_unsupported(&r) => retrieve_with(s, remote, probe, 1, false) + .await + .map(|_| false), + Err(r) => Err(r), + } +} + +// ── Passages as hits ───────────────────────────────────────────────────────── + +fn meta_str(m: &serde_json::Map, keys: &[&str]) -> Option { + keys.iter().find_map(|k| match m.get(*k)? { + Value::String(s) if !s.trim().is_empty() => Some(s.trim().to_string()), + Value::Number(n) => Some(n.to_string()), + _ => None, + }) +} + +const DOC_ID_KEYS: &[&str] = &[ + "x-amz-bedrock-kb-document-id", + "documentId", + "document_id", + "x-amz-bedrock-kb-source-uri", +]; +const TITLE_KEYS: &[&str] = &[ + "x-amz-bedrock-kb-title", + "title", + "Title", + "document_title", + "_document_title", +]; +const DATE_KEYS: &[&str] = &[ + "x-amz-bedrock-kb-updated-at", + "updated_at", + "updatedAt", + "last_modified", + "lastModified", + "_last_updated_at", + "modified", + "date", +]; + +/// A metadata date as `YYYY-MM-DD`: RFC 3339, a plain date, or epoch +/// seconds or milliseconds. Empty when there is none (no recency nudge). +fn as_of(raw: &str) -> String { + let raw = raw.trim(); + if let Ok(t) = chrono::DateTime::parse_from_rfc3339(raw) { + return t.format("%Y-%m-%d").to_string(); + } + if let Some(day) = raw.get(..10) { + if chrono::NaiveDate::parse_from_str(day, "%Y-%m-%d").is_ok() { + return day.to_string(); + } + } + if let Ok(n) = raw.parse::() { + let secs = if n > 100_000_000_000 { n / 1000 } else { n }; + if let Some(t) = chrono::DateTime::from_timestamp(secs, 0) { + return t.format("%Y-%m-%d").to_string(); + } + } + String::new() +} + +/// `s3://bucket/key` as (bucket, key). +fn s3_parts(uri: &str) -> Option<(&str, &str)> { + let rest = uri.strip_prefix("s3://")?; + let (bucket, key) = rest.split_once('/')?; + (!bucket.is_empty() && !key.is_empty()).then_some((bucket, key)) +} + +/// Bedrock's passages as hits of `base`, best first. Each passage's document +/// is its document id (else its source address), its place the title or S3 +/// object key, its date any updated date in its metadata, and its link the +/// original page (an S3 object links to the S3 console, which opens only +/// for people who have access there). +pub fn to_hits(base: &Base, remote: &Remote, passages: &[Passage]) -> Vec { + let mut out = Vec::new(); + for (i, p) in passages.iter().enumerate() { + if p.text.trim().is_empty() { + continue; + } + let source = if p.location.is_empty() { + meta_str(&p.metadata, &["x-amz-bedrock-kb-source-uri"]).unwrap_or_default() + } else { + p.location.clone() + }; + let document = meta_str(&p.metadata, DOC_ID_KEYS) + .or_else(|| (!source.is_empty()).then(|| source.clone())) + .or_else(|| meta_str(&p.metadata, &["x-amz-bedrock-kb-chunk-id"])) + .unwrap_or_else(|| format!("passage-{i}")); + let title = meta_str(&p.metadata, TITLE_KEYS); + let (loc, url) = match s3_parts(&source) { + Some((bucket, key)) => ( + key.to_string(), + format!( + "https://s3.console.aws.amazon.com/s3/object/{bucket}?region={}&prefix={}", + remote.region, + urlencoding::encode(key) + ), + ), + None => ( + title.clone().unwrap_or_else(|| source.clone()), + super::answer::original_url(&source).unwrap_or_default(), + ), + }; + let file_name = title.unwrap_or_else(|| { + loc.rsplit('/') + .find(|s| !s.is_empty()) + .unwrap_or(&document) + .to_string() + }); + out.push(Hit { + kb_id: base.id.clone(), + kb_name: base.name.clone(), + file_id: crate::truncate_str(&document, 512).to_string(), + file_name: crate::truncate_str(&file_name, 200).to_string(), + loc: crate::truncate_str(&loc, 300).to_string(), + as_of: meta_str(&p.metadata, DATE_KEYS) + .map(|d| as_of(&d)) + .unwrap_or_default(), + text: p.text.clone(), + score: p.score as f32, + authoritative: base.authoritative, + ord: i as u32, + url, + source_kind: super::SourceKind::BedrockKb.key().into(), + }); + } + out +} + +// ── The retriever ──────────────────────────────────────────────────────────── + +/// Searches connected Bedrock knowledge bases, as the team. `actor` names +/// the session in the team's AWS records (`brain`, `coder`). +pub struct Bedrock<'a> { + pub sts: &'a aws_sdk_sts::Client, + pub dynamo: &'a aws_sdk_dynamodb::Client, + /// The table of connected AWS accounts (`AWS_CONN#`). + pub accounts_table: &'a str, + pub actor: &'a str, +} + +#[async_trait::async_trait] +impl Retriever for Bedrock<'_> { + async fn retrieve( + &self, + team_id: &str, + base: &Base, + query: &str, + k: usize, + ) -> Result, String> { + let Backend::Remote(remote) = &base.backend else { + return Ok(Vec::new()); + }; + match remote.provider { + Provider::BedrockKb => {} + } + let s = session( + self.sts, + self.dynamo, + self.accounts_table, + team_id, + remote, + self.actor, + ) + .await + .map_err(|r| r.message)?; + let passages = retrieve_with(&s, remote, query, k, remote.hybrid) + .await + .map_err(|r| r.message)?; + Ok(to_hits(base, remote, &passages)) + } +} + +// ── Listing (self-hosted) ──────────────────────────────────────────────────── + +/// A knowledge base found in the install's own account. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Listed { + pub arn: String, + pub id: String, + pub name: String, + pub description: String, + /// `ACTIVE`, `CREATING`, `FAILED`, ... + pub status: String, + pub updated_at: String, +} + +/// The knowledge bases in the install's own account in `region`, with the +/// install's own role (`bedrock:ListKnowledgeBases`). +pub async fn list_install_bases(region: &str) -> Result, Refusal> { + use aws_sdk_bedrockagent::config::{BehaviorVersion, Credentials, Region}; + use aws_sdk_bedrockagent::error::ProvideErrorMetadata; + let own = aws::install_read_role().ok_or_else(|| { + Refusal::new( + "account", + "Only a self-hosted install lists its own knowledge bases.", + "Paste the knowledge base's ARN instead.", + ) + })?; + let account = own.split(':').nth(4).unwrap_or("").to_string(); + let s = aws::own_session(region).ok_or_else(|| { + Refusal::new( + "reach", + "This install's own AWS credentials aren't available here.", + "Paste the knowledge base's ARN instead.", + ) + })?; + let creds = Credentials::new( + &s.access_key_id, + &s.secret_access_key, + Some(s.session_token.clone()), + None, + "coderhelm-install-role", + ); + let client = aws_sdk_bedrockagent::Client::from_conf( + aws_sdk_bedrockagent::Config::builder() + .behavior_version(BehaviorVersion::latest()) + .region(Region::new(region.to_string())) + .credentials_provider(creds) + .build(), + ); + let mut out = Vec::new(); + let mut next: Option = None; + for _ in 0..10 { + let page = client + .list_knowledge_bases() + .max_results(100) + .set_next_token(next.take()) + .send() + .await + .map_err(|e| match e.as_service_error() { + Some(se) => { + let r = refusal(se.code().unwrap_or("Unknown"), se.message().unwrap_or("")); + if r.code == "access" { + Refusal::new( + "access", + "This install's role can't list knowledge bases yet.", + "It arrives with this install's next version update. Paste the knowledge base's ARN meanwhile.", + ) + } else { + r + } + } + None => refusal( + "", + &aws_sdk_bedrockagent::error::DisplayErrorContext(&e).to_string(), + ), + })?; + for kb in page.knowledge_base_summaries() { + let arn = KbArn { + region: region.to_string(), + account: account.clone(), + id: kb.knowledge_base_id().to_string(), + }; + out.push(Listed { + arn: arn.arn(), + id: arn.id, + name: kb.name().to_string(), + description: kb.description().unwrap_or("").to_string(), + status: kb.status().as_str().to_string(), + updated_at: kb.updated_at().to_string(), + }); + } + match page.next_token() { + Some(t) if !t.is_empty() => next = Some(t.to_string()), + _ => break, + } + } + out.sort_by_key(|a| a.name.to_lowercase()); + Ok(out) +} + +/// The ARNs of a team's knowledge bases connected in `account`, for the +/// log reader update that lets the role search them. +pub fn arns_in(bases: &[Base], account: &str) -> Vec { + let mut out: Vec = bases + .iter() + .filter_map(|b| b.remote()) + .filter(|r| matches!(&r.access, Access::Account { account: a } if a == account)) + .map(|r| r.target.clone()) + .collect(); + out.sort(); + out.dedup(); + out +} + +#[cfg(test)] +fn meta(pairs: &[(&str, Value)]) -> serde_json::Map { + pairs + .iter() + .map(|(k, v)| (k.to_string(), v.clone())) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + const ARN: &str = "arn:aws:bedrock:eu-west-1:111122223333:knowledge-base/ABCDE12345"; + + fn base() -> (Base, Remote) { + let remote = bedrock_remote( + &parse_kb_arn(ARN).unwrap(), + Access::Account { + account: "111122223333".into(), + }, + true, + ); + ( + Base { + id: "kb".into(), + name: "Runbooks".into(), + authoritative: true, + backend: Backend::Remote(remote.clone()), + ..Default::default() + }, + remote, + ) + } + + #[test] + fn the_arn_is_read_apart_and_its_region_is_the_one_used() { + let a = parse_kb_arn(&format!(" {ARN}\n")).unwrap(); + assert_eq!( + (a.region.as_str(), a.account.as_str(), a.id.as_str()), + ("eu-west-1", "111122223333", "ABCDE12345") + ); + assert_eq!(a.arn(), ARN); + let (_, r) = base(); + assert_eq!(r.region, "eu-west-1"); + for bad in [ + "", + "ABCDE12345", + "arn:aws:bedrock:eu-west-1:111122223333:agent/ABCDE12345", + "arn:aws:bedrock:eu-west-1:1111:knowledge-base/ABCDE12345", + "arn:aws:bedrock:eu-west-1:111122223333:knowledge-base/abcde12345", + "arn:aws:bedrock:eu-west-1:111122223333:knowledge-base/ABCDE1234", + "arn:aws:s3:eu-west-1:111122223333:knowledge-base/ABCDE12345", + "arn:aws:bedrock:EU:111122223333:knowledge-base/ABCDE12345", + "arn:aws:bedrock:eu-west-1:111122223333:knowledge-base/ABCDE12345/x", + ] { + let e = parse_kb_arn(bad).unwrap_err(); + assert!( + e.starts_with("That isn't a knowledge base ARN."), + "{bad}: {e}" + ); + } + } + + #[test] + fn refusals_are_said_in_plain_words() { + let r = refusal("AccessDeniedException", "User: arn:aws:sts::111122223333:assumed-role/CoderHelmLogReader/coderhelm-brain is not authorized to perform: bedrock:Retrieve on resource: arn:aws:bedrock:eu-west-1:111122223333:knowledge-base/ABCDE12345 because no identity-based policy allows the bedrock:Retrieve action"); + assert_eq!(r.code, "access"); + assert_eq!( + r.message, + "The role in your account does not allow Retrieve on this knowledge base." + ); + // A self-hosted install whose admin hasn't applied the access stack. + let r = refusal("AccessDeniedException", "User: arn:aws:sts::111122223333:assumed-role/coderhelm-prod-gateway/x is not authorized to perform: bedrock:Retrieve on resource: arn:aws:bedrock:us-east-1:111122223333:knowledge-base/ABCDE12345 because no permissions boundary allows the bedrock:Retrieve action"); + assert_eq!(r.code, "boundary"); + assert!(r + .message + .contains("permission change an AWS admin hasn't applied")); + assert!(r.fix.contains("Settings, System")); + // A MANAGED base in another account whose resource policy is missing. + let r = refusal( + "AccessDeniedException", + "... because no resource-based policy allows the bedrock:Retrieve action", + ); + assert_eq!(r.code, "resource_policy"); + assert!(r.fix.contains("bedrock:Retrieve")); + let r = refusal( + "AccessDeniedException", + "... with an explicit deny in a service control policy", + ); + assert_eq!(r.code, "scp"); + assert_eq!( + refusal("ResourceNotFoundException", "kb not found").code, + "not_found" + ); + assert_eq!(refusal("ThrottlingException", "slow").code, "busy"); + assert_eq!( + refusal("DependencyFailedException", "aoss down").code, + "store" + ); + // An account number or ARN in AWS's message never reaches the page. + let r = refusal("ValidationException", "Knowledge base arn:aws:bedrock:eu-west-1:111122223333:knowledge-base/ABCDE12345 is not ready"); + assert!(!r.message.contains("111122223333"), "{}", r.message); + let r = refusal("", "dispatch failure: timeout"); + assert_eq!(r.code, "reach"); + assert!(r.fix.contains("VPC endpoint")); + for r in [refusal("AccessDeniedException", "x"), refusal("Weird", "y")] { + assert!(!format!("{}{}", r.message, r.fix).contains('\u{2192}')); + } + assert!(hybrid_unsupported(&refusal( + "ValidationException", + "HYBRID search type is not supported for this vector store" + ))); + assert!(!hybrid_unsupported(&refusal( + "ValidationException", + "query is too long" + ))); + } + + #[test] + fn the_install_account_uses_the_install_role_and_others_the_teams_role() { + let arn = parse_kb_arn(ARN).unwrap(); + let own = "arn:aws:iam::111122223333:role/coderhelm-prod-gateway-1a2b"; + assert_eq!(access_for(&arn, Some(own), &[]).unwrap(), Access::Install); + let connected = AwsAccount { + account: "111122223333".into(), + role_arn: "arn:aws:iam::111122223333:role/CoderHelmLogReader".into(), + external_id: "coderhelm-x".into(), + region: "us-east-1".into(), + ..Default::default() + }; + // Hosted (no install role): the team's connected role in that account. + assert_eq!( + access_for(&arn, None, std::slice::from_ref(&connected)).unwrap(), + Access::Account { + account: "111122223333".into() + } + ); + // An install in another account: the team's role there. + assert_eq!( + access_for( + &arn, + Some("arn:aws:iam::999988887777:role/x"), + std::slice::from_ref(&connected) + ) + .unwrap(), + Access::Account { + account: "111122223333".into() + } + ); + // An account nobody connected: said plainly. + let r = access_for(&arn, None, &[]).unwrap_err(); + assert_eq!(r.code, "account"); + assert!(r.message.contains("111122223333 isn't connected")); + } + + #[test] + fn passages_become_hits_with_document_place_date_and_link() { + let (b, r) = base(); + let ps = vec![ + Passage { + text: "Restart the consumer before draining the queue.".into(), + location_type: "S3".into(), + location: "s3://ops-docs/runbooks/queues/drain.md".into(), + metadata: meta(&[ + ( + "x-amz-bedrock-kb-source-uri", + json!("s3://ops-docs/runbooks/queues/drain.md"), + ), + ("x-amz-bedrock-kb-chunk-id", json!("c-1")), + ("updated_at", json!("2026-09-30T10:00:00Z")), + ]), + score: 0.83, + }, + Passage { + text: "On-call rotates every Monday.".into(), + location_type: "CONFLUENCE".into(), + location: "https://example.atlassian.net/wiki/spaces/OPS/pages/1".into(), + metadata: meta(&[ + ("x-amz-bedrock-kb-document-id", json!("doc-77")), + ("title", json!("On-call")), + ("lastModified", json!(1_790_000_000_000i64)), + ]), + score: 0.5, + }, + Passage { + text: " ".into(), + ..Default::default() + }, + Passage { + text: "A custom document.".into(), + location_type: "CUSTOM".into(), + location: "my-doc".into(), + ..Default::default() + }, + ]; + let hits = to_hits(&b, &r, &ps); + assert_eq!(hits.len(), 3, "an empty passage is dropped"); + let s3 = &hits[0]; + assert_eq!(s3.file_id, "s3://ops-docs/runbooks/queues/drain.md"); + assert_eq!(s3.loc, "runbooks/queues/drain.md"); + assert_eq!(s3.file_name, "drain.md"); + assert_eq!(s3.as_of, "2026-09-30"); + assert_eq!(s3.url, "https://s3.console.aws.amazon.com/s3/object/ops-docs?region=eu-west-1&prefix=runbooks%2Fqueues%2Fdrain.md"); + assert_eq!(s3.source_kind, "bedrock_kb"); + assert_eq!( + (s3.kb_id.as_str(), s3.kb_name.as_str(), s3.authoritative), + ("kb", "Runbooks", true) + ); + let wiki = &hits[1]; + assert_eq!(wiki.file_id, "doc-77"); + assert_eq!(wiki.file_name, "On-call"); + assert_eq!(wiki.loc, "On-call"); + assert_eq!( + wiki.url, + "https://example.atlassian.net/wiki/spaces/OPS/pages/1" + ); + assert_eq!(wiki.as_of, "2026-09-21"); + let custom = &hits[2]; + assert_eq!(custom.file_id, "my-doc"); + assert_eq!(custom.url, "", "an id is not a link"); + assert_eq!(custom.as_of, "", "no date, no recency nudge"); + } + + #[test] + fn the_update_names_only_this_accounts_connected_bases() { + let (b, _) = base(); + let other = Base { + backend: Backend::Remote(bedrock_remote( + &parse_kb_arn("arn:aws:bedrock:us-east-1:444455556666:knowledge-base/ZZZZZ00000") + .unwrap(), + Access::Account { + account: "444455556666".into(), + }, + true, + )), + ..b.clone() + }; + let install = Base { + backend: Backend::Remote(bedrock_remote( + &parse_kb_arn(ARN).unwrap(), + Access::Install, + true, + )), + ..b.clone() + }; + let local = Base::default(); + assert_eq!( + arns_in(&[b.clone(), b, other, install, local], "111122223333"), + [ARN] + ); + } +} diff --git a/services/common/src/knowledge/search.rs b/services/common/src/knowledge/search.rs index 3963be7e6..cec489093 100644 --- a/services/common/src/knowledge/search.rs +++ b/services/common/src/knowledge/search.rs @@ -184,6 +184,24 @@ pub trait Store: Send + Sync { async fn index(&self, team_id: &str, key: &str) -> Result, String>; } +/// Searches a base connected in place ([`super::Backend::Remote`]) where it +/// lives: the provider ranks, Coderhelm only merges. Takes the team, like +/// every [`Store`] method, and reaches the base only with that team's own +/// access (its role and private ID), so another team's id finds nothing. +#[async_trait::async_trait] +pub trait Retriever: Send + Sync { + /// Up to `k` passages of the team's remote `base` for `query`, best + /// first. `kb_id`, `kb_name` and `authoritative` of the hits are set by + /// [`search`] from the base, whatever this returns. + async fn retrieve( + &self, + team_id: &str, + base: &Base, + query: &str, + k: usize, + ) -> Result, String>; +} + /// Turns text into a vector. #[async_trait::async_trait] pub trait Embedder: Send + Sync { @@ -362,13 +380,28 @@ pub struct Stale { pub version: u32, } +/// A connected base that couldn't be searched this time, and why in plain +/// words. +#[derive(Debug, Clone, PartialEq)] +pub struct Unreached { + pub kb_id: String, + pub kb_name: String, + pub reason: String, +} + /// What a search found. #[derive(Debug, Clone, Default, PartialEq)] pub struct Found { pub hits: Vec, pub stale: Vec, + /// Connected bases that didn't answer; the others' passages still count. + pub unreached: Vec, } +/// How many passages a connected base is asked for: anything ranked lower +/// is under [`MIN_FUSED`] anyway. +pub const REMOTE_DEPTH: usize = 30; + /// The vector list keeps passages at least this similar. pub const MIN_COSINE: f32 = 0.25; /// The keyword list keeps passages holding at least this share of the @@ -533,16 +566,14 @@ pub fn keyword_list(query: &str, cands: &[Candidate]) -> Vec<(usize, f32)> { out } -/// Reciprocal rank fusion of the two lists, nudged by recency and by a -/// source of truth, cut at [`MIN_FUSED`]. Returns `(position, score)`, best -/// first. -pub fn fuse( - vector: &[(usize, f32)], - keyword: &[(usize, f32)], - cands: &[Candidate], -) -> Vec<(usize, f32)> { +/// Reciprocal rank fusion of ranked lists (the local vector and keyword +/// lists, and one list per connected base, ranked where it lives), nudged +/// by recency and by a source of truth, cut at [`MIN_FUSED`]. Only ranks +/// count, so lists scored on different scales (a Titan cosine, a BM25 sum, +/// a Bedrock score) merge fairly. Returns `(position, score)`, best first. +pub fn fuse(lists: &[&[(usize, f32)]], cands: &[Candidate]) -> Vec<(usize, f32)> { let mut fused: HashMap = HashMap::new(); - for list in [vector, keyword] { + for list in lists { for (rank, (i, _)) in list.iter().enumerate() { *fused.entry(*i).or_default() += 1.0 / (RRF_K + rank as f32 + 1.0); } @@ -568,12 +599,28 @@ fn age_days(as_of: &str, now: chrono::DateTime) -> f32 { .unwrap_or(0.0) } +/// One passage in the fused ranking: from a local index, or as a connected +/// base returned it. +enum Entry<'a> { + Local(&'a Base, &'a FileMeta, &'a IndexedChunk), + Remote(&'a Base, &'a Hit), +} + /// The best passages for `query` in the team's bases `kb_ids`, at most `k`. /// Each base is read by the team's key, so an id from another team (or a /// made-up one) finds nothing. +/// +/// Local bases are ranked here (vector and keyword lists); each connected +/// base is searched where it lives, all at once, and its answer joins the +/// fusion as one more ranked list. The question is embedded only when a +/// local file will be scored against it. A connected base that doesn't +/// answer is reported in [`Found::unreached`]; the search fails only when +/// nothing could be searched at all. +#[allow(clippy::too_many_arguments)] pub async fn search( store: &dyn Store, embedder: &dyn Embedder, + retriever: &dyn Retriever, team_id: &str, kb_ids: &[String], query: &str, @@ -586,10 +633,17 @@ pub async fn search( return Ok(found); } let mut files: Vec<(Base, FileMeta, String)> = Vec::new(); + let mut remote: Vec = Vec::new(); for id in kb_ids { let Some(base) = store.base(team_id, id).await? else { continue; }; + if base.remote().is_some() { + if !remote.iter().any(|b| b.id == base.id) { + remote.push(base); + } + continue; + } for f in store.files(team_id, &base.id).await? { if f.kb_id != base.id { continue; @@ -602,34 +656,76 @@ pub async fn search( } } } - if files.is_empty() { + if files.is_empty() && remote.is_empty() { return Ok(found); } - let qv = embedder.embed(crate::truncate_str(query, 8_000)).await?; - let mut loaded: Vec<(Base, FileMeta, Arc)> = Vec::new(); - for (base, file, key) in files { - match store.index(team_id, &key).await { - Ok(i) if i.model != embedder.model() || i.dims != qv.len() => { - tracing::warn!(kb = %base.id, file = %file.id, model = %i.model, dims = i.dims, - "Knowledge index from another embedding model; needs re-embedding"); - found.stale.push(Stale { + + // Every connected base at once, while the local side embeds and loads. + let asked = futures::future::join_all( + remote + .iter() + .map(|b| retriever.retrieve(team_id, b, query, REMOTE_DEPTH)), + ); + let local = async { + if files.is_empty() { + return Ok((Vec::new(), Vec::new(), Vec::new())); + } + let qv = embedder.embed(crate::truncate_str(query, 8_000)).await?; + let mut loaded: Vec<(Base, FileMeta, Arc)> = Vec::new(); + let mut stale = Vec::new(); + for (base, file, key) in &files { + match store.index(team_id, key).await { + Ok(i) if i.model != embedder.model() || i.dims != qv.len() => { + tracing::warn!(kb = %base.id, file = %file.id, model = %i.model, dims = i.dims, + "Knowledge index from another embedding model; needs re-embedding"); + stale.push(Stale { + kb_id: base.id.clone(), + file_id: file.id.clone(), + version: file.ready_version, + }); + } + Ok(i) => loaded.push((base.clone(), file.clone(), i)), + Err(e) => { + tracing::warn!(kb = %base.id, file = %file.id, error = %e, "Knowledge index unreadable; skipped"); + } + } + } + Ok::<_, String>((qv, loaded, stale)) + }; + let (answers, local) = futures::join!(asked, local); + let (qv, loaded, stale) = local?; + found.stale = stale; + + let mut remote_hits: Vec<(&Base, Vec)> = Vec::new(); + for (base, answer) in remote.iter().zip(answers) { + match answer { + Ok(hits) => remote_hits.push((base, hits)), + Err(reason) => { + tracing::warn!(kb = %base.id, error = %reason, "Connected knowledge base didn't answer; skipped"); + found.unreached.push(Unreached { kb_id: base.id.clone(), - file_id: file.id.clone(), - version: file.ready_version, + kb_name: base.name.clone(), + reason, }); } - Ok(i) => loaded.push((base, file, i)), - Err(e) => { - tracing::warn!(kb = %base.id, file = %file.id, error = %e, "Knowledge index unreadable; skipped"); - } } } - let mut owners: Vec<(&Base, &FileMeta, &IndexedChunk)> = Vec::new(); + if files.is_empty() && remote_hits.is_empty() { + // Nothing could be searched: say why rather than "nothing matched". + let why: Vec = found + .unreached + .iter() + .map(|u| format!("{}: {}", u.kb_name, u.reason)) + .collect(); + return Err(why.join(" ")); + } + + let mut entries: Vec = Vec::new(); let mut cands: Vec = Vec::new(); for (base, file, index) in &loaded { let age = age_days(&file.as_of, now); for c in &index.chunks { - owners.push((base, file, c)); + entries.push(Entry::Local(base, file, c)); cands.push(Candidate { text: &c.text, loc: &c.loc, @@ -639,39 +735,77 @@ pub async fn search( }); } } - let ranked = fuse( - &vector_list(&qv, &cands), - &keyword_list(query, &cands), - &cands, - ); - // No more than three passages from one file, so one long document - // doesn't crowd out the others. - let mut per_file: HashMap<&str, usize> = HashMap::new(); + let n_local = cands.len(); + // The local lists rank local passages only; each connected base's + // passages come ranked already, as their own list. + let mut lists: Vec> = vec![ + vector_list(&qv, &cands[..n_local]), + keyword_list(query, &cands[..n_local]), + ]; + for (base, hits) in &remote_hits { + let mut list = Vec::new(); + for h in hits.iter().take(REMOTE_DEPTH) { + if h.text.trim().is_empty() { + continue; + } + list.push((cands.len(), h.score)); + entries.push(Entry::Remote(base, h)); + cands.push(Candidate { + text: &h.text, + loc: &h.loc, + vector: &[], + age_days: age_days(&h.as_of, now), + authoritative: base.authoritative, + }); + } + lists.push(list); + } + let refs: Vec<&[(usize, f32)]> = lists.iter().map(Vec::as_slice).collect(); + let ranked = fuse(&refs, &cands); + // No more than three passages from one file (a connected base's + // document), so one long document doesn't crowd out the others. + let mut per_file: HashMap<(&str, &str), usize> = HashMap::new(); for (i, score) in ranked { - let (base, file, c) = owners[i]; - let n = per_file.entry(file.id.as_str()).or_default(); + let hit = match entries[i] { + Entry::Local(base, file, c) => Hit { + kb_id: base.id.clone(), + kb_name: base.name.clone(), + file_id: file.id.clone(), + file_name: file.name.clone(), + loc: c.loc.clone(), + as_of: file.as_of.clone(), + text: c.text.clone(), + score, + authoritative: base.authoritative, + ord: c.ord, + url: file.url.clone(), + source_kind: if file.is_synced() { + file.kind.clone() + } else { + String::new() + }, + }, + // The base's own name, flag and kind, whatever the retriever said. + Entry::Remote(base, h) => Hit { + kb_id: base.id.clone(), + kb_name: base.name.clone(), + score, + authoritative: base.authoritative, + source_kind: super::SourceKind::BedrockKb.key().into(), + ..h.clone() + }, + }; + let n = per_file + .entry(match entries[i] { + Entry::Local(base, file, _) => (base.id.as_str(), file.id.as_str()), + Entry::Remote(base, h) => (base.id.as_str(), h.file_id.as_str()), + }) + .or_default(); *n += 1; if *n > 3 { continue; } - found.hits.push(Hit { - kb_id: base.id.clone(), - kb_name: base.name.clone(), - file_id: file.id.clone(), - file_name: file.name.clone(), - loc: c.loc.clone(), - as_of: file.as_of.clone(), - text: c.text.clone(), - score, - authoritative: base.authoritative, - ord: c.ord, - url: file.url.clone(), - source_kind: if file.is_synced() { - file.kind.clone() - } else { - String::new() - }, - }); + found.hits.push(hit); if found.hits.len() >= k { break; } @@ -768,7 +902,112 @@ pub mod testing { } } + /// What a connected base answers, per `(team, base)`. + type Answers = HashMap<(String, String), Result, String>>; + + /// A connected base's answers, set per team and base: a team only ever + /// gets the answers set for it, like the real one (its own role). + #[derive(Default)] + pub struct FakeRetriever { + pub answers: Mutex, + /// `(team, base)` of every call, in order. + pub calls: Mutex>, + } + + impl FakeRetriever { + /// What base `kb_id` of `team_id` answers. + pub fn answer(&self, team_id: &str, kb_id: &str, a: Result, String>) { + self.answers + .lock() + .unwrap() + .insert((team_id.into(), kb_id.into()), a); + } + } + + #[async_trait::async_trait] + impl Retriever for FakeRetriever { + async fn retrieve( + &self, + team_id: &str, + base: &Base, + _query: &str, + k: usize, + ) -> Result, String> { + self.calls + .lock() + .unwrap() + .push((team_id.into(), base.id.clone())); + match self + .answers + .lock() + .unwrap() + .get(&(team_id.to_string(), base.id.clone())) + { + Some(Ok(h)) => Ok(h.iter().take(k).cloned().collect()), + Some(Err(e)) => Err(e.clone()), + None => Ok(Vec::new()), + } + } + } + + /// The word embedder, counting its calls. + #[derive(Default)] + pub struct CountingEmbedder { + pub calls: std::sync::atomic::AtomicUsize, + } + + #[async_trait::async_trait] + impl Embedder for CountingEmbedder { + fn model(&self) -> &str { + TEST_MODEL + } + async fn embed(&self, text: &str) -> Result, String> { + self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(embed_words(text)) + } + } + + /// A base connected in place (a Bedrock knowledge base in `account`). + pub fn remote_base(id: &str, name: &str, account: &str) -> Base { + Base { + id: id.into(), + name: name.into(), + read_role: "member".into(), + backend: crate::knowledge::Backend::Remote(crate::knowledge::Remote { + provider: crate::knowledge::Provider::BedrockKb, + target: format!("arn:aws:bedrock:us-east-1:{account}:knowledge-base/ABCDE12345"), + region: "us-east-1".into(), + access: crate::knowledge::Access::Account { + account: account.into(), + }, + hybrid: true, + }), + ..Default::default() + } + } + + /// A passage as a connected base returns it. + pub fn remote_hit(doc: &str, text: &str) -> Hit { + Hit { + file_id: doc.into(), + file_name: doc.rsplit('/').next().unwrap_or(doc).into(), + loc: doc.into(), + text: text.into(), + score: 0.5, + ..Default::default() + } + } + impl MemoryStore { + /// Adds a base with no files (a connected one). + pub fn add_base(&self, team_id: &str, base: &Base) { + let mut b = self.bases.lock().unwrap(); + let list = b.entry(team_id.to_string()).or_default(); + if !list.iter().any(|x| x.id == base.id) { + list.push(base.clone()); + } + } + /// Adds a ready file whose passages are `texts`. pub fn add_file( &self, @@ -943,6 +1182,7 @@ mod tests { let found = search( &store, &WordEmbedder, + &FakeRetriever::default(), "t", &["kb".into()], "parental leave weeks", @@ -1014,9 +1254,18 @@ mod tests { .collect(); assert!(vector_list(&qv, &cands).is_empty()); // Hybrid search finds it through the keyword list. - let found = search(&store, &WordEmbedder, "t", &["kb_ops".into()], q, 5, now()) - .await - .unwrap(); + let found = search( + &store, + &WordEmbedder, + &FakeRetriever::default(), + "t", + &["kb_ops".into()], + q, + 5, + now(), + ) + .await + .unwrap(); assert_eq!(found.hits.len(), 1, "{:?}", found.hits); assert!(found.hits[0].text.starts_with("ERR-4021")); } @@ -1050,7 +1299,7 @@ mod tests { let v = vector_list(&qv, &cands); let k = keyword_list(q, &cands); assert!(v.iter().all(|(i, _)| *i == 0) && k.iter().all(|(i, _)| *i == 0)); - let fused = fuse(&v, &k, &cands); + let fused = fuse(&[&v, &k], &cands); assert_eq!(fused.iter().map(|(i, _)| *i).collect::>(), [0]); // One word in common out of many is not enough for the keyword list. let thin = [Candidate { @@ -1072,7 +1321,7 @@ mod tests { authoritative: false, }) .collect(); - let fused = fuse(&deep, &[], &many); + let fused = fuse(&[&deep, &[]], &many); assert_eq!(fused.len(), 30); assert!(fused.iter().all(|(i, _)| *i < 30)); } @@ -1094,13 +1343,13 @@ mod tests { mk(900.0, true), ]; // 0 is first in both lists; 1 only in one. - let fused = fuse(&[(0, 0.9), (1, 0.8)], &[(0, 5.0)], &cands); + let fused = fuse(&[&[(0, 0.9), (1, 0.8)], &[(0, 5.0)]], &cands); assert_eq!(fused[0].0, 0); // Same ranks: the source of truth outranks the plain old one. - let fused = fuse(&[(2, 0.9)], &[(3, 5.0)], &cands); + let fused = fuse(&[&[(2, 0.9)], &[(3, 5.0)]], &cands); assert_eq!(fused[0].0, 3); // Same ranks: the newer one outranks the older one. - let fused = fuse(&[(2, 0.9)], &[(1, 5.0)], &cands); + let fused = fuse(&[&[(2, 0.9)], &[(1, 5.0)]], &cands); assert_eq!(fused[0].0, 1); } @@ -1122,6 +1371,7 @@ mod tests { let found = search( &store, &WordEmbedder, + &FakeRetriever::default(), "team_a", &["kb_hr".into()], "How many weeks is parental leave?", @@ -1155,6 +1405,7 @@ mod tests { let b = search( &store, &WordEmbedder, + &FakeRetriever::default(), "team_b", &["kb_b".into()], q, @@ -1168,6 +1419,7 @@ mod tests { let a = search( &store, &WordEmbedder, + &FakeRetriever::default(), "team_a", &["kb_b".into()], q, @@ -1190,6 +1442,7 @@ mod tests { let a = search( &store, &WordEmbedder, + &FakeRetriever::default(), "team_a", &["kb_b".into()], q, @@ -1219,6 +1472,7 @@ mod tests { let found = search( &store, &WordEmbedder, + &FakeRetriever::default(), "t", &["kb_hr".into()], "Kubernetes ingress certificate rotation", @@ -1228,13 +1482,20 @@ mod tests { .await .unwrap(); assert!(found.hits.is_empty(), "{:?}", found.hits); - assert!( - search(&store, &WordEmbedder, "t", &[], "Parental leave", 5, now()) - .await - .unwrap() - .hits - .is_empty() - ); + assert!(search( + &store, + &WordEmbedder, + &FakeRetriever::default(), + "t", + &[], + "Parental leave", + 5, + now() + ) + .await + .unwrap() + .hits + .is_empty()); } #[tokio::test] @@ -1253,6 +1514,7 @@ mod tests { let found = search( &store, &WordEmbedder, + &FakeRetriever::default(), "t", &["kb".into()], "parental leave weeks", @@ -1284,6 +1546,7 @@ mod tests { let found = search( &store, &WordEmbedder, + &FakeRetriever::default(), "t", &["kb".into()], "deploy freeze friday", @@ -1295,4 +1558,334 @@ mod tests { assert!(found.hits.iter().filter(|h| h.file_id == "big").count() <= 3); assert!(found.hits.iter().any(|h| h.file_id == "small")); } + + // ── Connected bases ───────────────────────────────────────────────── + + #[tokio::test] + async fn a_connected_base_joins_the_fusion_as_one_more_ranked_list() { + let store = MemoryStore::default(); + let local = base("kb_local", "Handbook"); + store.add_file( + "t", + &local, + "f1", + "Leave.md", + "2026-05-01", + &["Parental leave is sixteen weeks fully paid."], + ); + let remote = remote_base("kb_aws", "Runbooks in AWS", "111122223333"); + store.add_base("t", &remote); + let retriever = FakeRetriever::default(); + retriever.answer( + "t", + "kb_aws", + Ok(vec![ + // Bedrock's own ranking: best first, its own scale of score. + Hit { + as_of: "2026-10-01".into(), + url: "https://wiki.example.org/leave".into(), + ..remote_hit( + "s3://docs/hr/leave-policy.pdf", + "Parental leave can be split into two blocks of eight weeks.", + ) + }, + remote_hit( + "s3://docs/hr/holidays.pdf", + "Public holidays follow the office's country.", + ), + ]), + ); + let found = search( + &store, + &WordEmbedder, + &retriever, + "t", + &["kb_local".into(), "kb_aws".into()], + "parental leave weeks", + 10, + now(), + ) + .await + .unwrap(); + // Both sides are in one ranking; the remote hit carries the base's + // own name and the Bedrock kind, its document and its link. + let from_aws: Vec<&Hit> = found.hits.iter().filter(|h| h.kb_id == "kb_aws").collect(); + assert!( + found.hits.iter().any(|h| h.kb_id == "kb_local"), + "{:?}", + found.hits + ); + assert_eq!(from_aws.len(), 2, "{:?}", found.hits); + assert_eq!(from_aws[0].kb_name, "Runbooks in AWS"); + assert_eq!(from_aws[0].source_kind, "bedrock_kb"); + assert_eq!(from_aws[0].file_id, "s3://docs/hr/leave-policy.pdf"); + assert_eq!(from_aws[0].url, "https://wiki.example.org/leave"); + assert!(from_aws[0].text.contains("two blocks")); + // Its first passage outranks its second: Bedrock's order is kept. + let pos = |t: &str| found.hits.iter().position(|h| h.text.contains(t)).unwrap(); + assert!(pos("two blocks") < pos("Public holidays")); + // The base was asked once, as this team. + assert_eq!( + *retriever.calls.lock().unwrap(), + [("t".to_string(), "kb_aws".to_string())] + ); + // A list ranked elsewhere counts by rank only: the same rank in the + // remote list and in one local list scores the same. + let v = vec![0.0f32; 2]; + let mk = || Candidate { + text: "", + loc: "", + vector: &v, + age_days: 0.0, + authoritative: false, + }; + let cands = [mk(), mk()]; + let fused = fuse(&[&[(0, 0.91)], &[], &[(1, 1234.0)]], &cands); + assert!((fused[0].1 - fused[1].1).abs() < 1e-9, "{fused:?}"); + } + + #[tokio::test] + async fn a_connected_document_gives_at_most_three_passages() { + let store = MemoryStore::default(); + let remote = remote_base("kb_aws", "Docs in AWS", "111122223333"); + store.add_base("t", &remote); + let retriever = FakeRetriever::default(); + let mut hits: Vec = (0..6) + .map(|i| { + remote_hit( + "doc-big", + &format!("Deploy freeze rules part {i}: no deploys on Fridays."), + ) + }) + .collect(); + hits.push(remote_hit( + "doc-small", + "Deploy freeze starts Friday at noon.", + )); + retriever.answer("t", "kb_aws", Ok(hits)); + let found = search( + &store, + &WordEmbedder, + &retriever, + "t", + &["kb_aws".into()], + "deploy freeze friday", + 10, + now(), + ) + .await + .unwrap(); + assert_eq!( + found.hits.iter().filter(|h| h.file_id == "doc-big").count(), + 3 + ); + assert!(found.hits.iter().any(|h| h.file_id == "doc-small")); + // The cap is per base and document: the same document id in another + // base is another document. + let other = remote_base("kb_aws2", "More docs", "111122223333"); + store.add_base("t", &other); + retriever.answer( + "t", + "kb_aws2", + Ok((0..3) + .map(|i| remote_hit("doc-big", &format!("Freeze note {i}"))) + .collect()), + ); + let found = search( + &store, + &WordEmbedder, + &retriever, + "t", + &["kb_aws".into(), "kb_aws2".into()], + "deploy freeze friday", + 20, + now(), + ) + .await + .unwrap(); + assert_eq!( + found.hits.iter().filter(|h| h.file_id == "doc-big").count(), + 6 + ); + } + + #[tokio::test] + async fn only_connected_bases_never_embed_the_question() { + let store = MemoryStore::default(); + store.add_base("t", &remote_base("kb_aws", "Docs in AWS", "111122223333")); + let retriever = FakeRetriever::default(); + retriever.answer( + "t", + "kb_aws", + Ok(vec![remote_hit( + "d", + "Rotate the signing keys every ninety days.", + )]), + ); + let titan = CountingEmbedder::default(); + let found = search( + &store, + &titan, + &retriever, + "t", + &["kb_aws".into()], + "signing keys", + 5, + now(), + ) + .await + .unwrap(); + assert_eq!(found.hits.len(), 1); + assert_eq!(titan.calls.load(std::sync::atomic::Ordering::SeqCst), 0); + // With a local file as well, the question is embedded once. + let local = base("kb_local", "Handbook"); + store.add_file( + "t", + &local, + "f", + "Keys.md", + "2026-01-01", + &["Signing keys rotate quarterly."], + ); + search( + &store, + &titan, + &retriever, + "t", + &["kb_aws".into(), "kb_local".into()], + "signing keys", + 5, + now(), + ) + .await + .unwrap(); + assert_eq!(titan.calls.load(std::sync::atomic::Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn a_team_never_reaches_another_teams_connected_base() { + let store = MemoryStore::default(); + let theirs = remote_base("kb_b", "Team B in AWS", "444455556666"); + store.add_base("team_b", &theirs); + let retriever = FakeRetriever::default(); + retriever.answer( + "team_b", + "kb_b", + Ok(vec![remote_hit( + "d", + "The enterprise discount floor is forty percent.", + )]), + ); + let q = "enterprise discount floor"; + let b = search( + &store, + &WordEmbedder, + &retriever, + "team_b", + &["kb_b".into()], + q, + 5, + now(), + ) + .await + .unwrap(); + assert_eq!(b.hits.len(), 1); + // Team A naming team B's base id: the base isn't team A's, so its + // retriever is never even asked. + retriever.calls.lock().unwrap().clear(); + let a = search( + &store, + &WordEmbedder, + &retriever, + "team_a", + &["kb_b".into()], + q, + 5, + now(), + ) + .await + .unwrap(); + assert!(a.hits.is_empty()); + assert!(retriever.calls.lock().unwrap().is_empty()); + // A base of team A's with the same id is asked as team A, and gets + // team A's answer only. + store.add_base( + "team_a", + &remote_base("kb_b", "Team A in AWS", "111122223333"), + ); + let a = search( + &store, + &WordEmbedder, + &retriever, + "team_a", + &["kb_b".into()], + q, + 5, + now(), + ) + .await + .unwrap(); + assert!(a.hits.is_empty(), "{:?}", a.hits); + assert_eq!( + *retriever.calls.lock().unwrap(), + [("team_a".to_string(), "kb_b".to_string())] + ); + } + + #[tokio::test] + async fn a_connected_base_that_fails_is_named_and_the_rest_still_answer() { + let store = MemoryStore::default(); + let local = base("kb_local", "Handbook"); + store.add_file( + "t", + &local, + "f", + "Leave.md", + "2026-01-01", + &["Parental leave is sixteen weeks."], + ); + store.add_base("t", &remote_base("kb_aws", "Docs in AWS", "111122223333")); + let retriever = FakeRetriever::default(); + let why = crate::knowledge::remote::refusal("AccessDeniedException", "User: arn:aws:sts::111122223333:assumed-role/CoderHelmLogReader/x is not authorized to perform: bedrock:Retrieve on resource: arn:aws:bedrock:us-east-1:111122223333:knowledge-base/ABCDE12345 because no identity-based policy allows the bedrock:Retrieve action"); + retriever.answer("t", "kb_aws", Err(why.message.clone())); + let found = search( + &store, + &WordEmbedder, + &retriever, + "t", + &["kb_local".into(), "kb_aws".into()], + "parental leave weeks", + 5, + now(), + ) + .await + .unwrap(); + assert_eq!(found.hits.len(), 1); + assert_eq!(found.unreached.len(), 1); + assert_eq!(found.unreached[0].kb_name, "Docs in AWS"); + assert!( + found.unreached[0] + .reason + .contains("does not allow Retrieve on this knowledge base"), + "{}", + found.unreached[0].reason + ); + // Only the failing connected base: the search fails, in plain words. + let err = search( + &store, + &WordEmbedder, + &retriever, + "t", + &["kb_aws".into()], + "parental leave", + 5, + now(), + ) + .await + .unwrap_err(); + assert!( + err.starts_with("Docs in AWS: The role in your account does not allow Retrieve"), + "{err}" + ); + } } diff --git a/services/common/src/live/aws_account.rs b/services/common/src/live/aws_account.rs index 3d296bd17..a2e98338d 100644 --- a/services/common/src/live/aws_account.rs +++ b/services/common/src/live/aws_account.rs @@ -67,6 +67,10 @@ pub struct AwsAccount { pub abilities: Abilities, /// The last live check of this release's permissions, if any. pub permissions: Option, + /// The ARNs of the team's knowledge bases connected in this account + /// (filled by the caller, never stored here): an update keeps the role + /// able to search them. + pub knowledge_bases: Vec, } fn s(item: &Item, k: &str) -> String { @@ -115,6 +119,7 @@ impl AwsAccount { region }, status: s(item, "status"), + knowledge_bases: Vec::new(), permissions: item .get("permissions_check") .and_then(|v| v.as_s().ok()) @@ -303,7 +308,7 @@ impl AwsAccount { "skipped": a.airflow_skip, "environments": self.airflow_environments(), }, - "permissions": self.permissions.as_ref().map(|p| p.view(false, &crate::public_urls::log_reader_template_url())), + "permissions": self.permissions.as_ref().map(|p| p.view_with(false, &crate::public_urls::log_reader_template_url(), &self.knowledge_bases)), }) } diff --git a/services/common/src/live/permissions.rs b/services/common/src/live/permissions.rs index caea40a4b..cb615b6c1 100644 --- a/services/common/src/live/permissions.rs +++ b/services/common/src/live/permissions.rs @@ -221,6 +221,17 @@ impl PermissionCheck { /// missing), the one-click update and any problem. `template_url` is /// the install's role template ([`crate::public_urls::log_reader_template_url`]). pub fn view(&self, pressed: bool, template_url: &str) -> Value { + self.view_with(pressed, template_url, &[]) + } + + /// [`Self::view`], with the ARNs of the team's knowledge bases connected + /// in this account: the update keeps the role able to search them. + pub fn view_with( + &self, + pressed: bool, + template_url: &str, + knowledge_bases: &[String], + ) -> Value { let missing: Vec = self .missing .iter() @@ -256,8 +267,8 @@ impl PermissionCheck { .flatten() .map(|t| { json!({ - "url": log_reader::update_url(&t, &self.region), - "stack_name": log_reader::update_stack_name(), + "url": log_reader::update_url(&t, &self.region, knowledge_bases), + "stack_name": log_reader::update_stack_name_for(knowledge_bases), "template_url": t, "sign_in_account": self.account, "stacks_url": log_reader::stack_list_url(&self.region), @@ -388,7 +399,7 @@ async fn simulate(s: &Session, target: &AwsTarget) -> Result, boo let iam = client!(aws_sdk_iam, s, "us-east-1".to_string()); let account = target.account(); let mut groups: Vec<(String, Vec)> = Vec::new(); - for a in log_reader::all_actions() { + for a in log_reader::checked_actions() { let r = simulated_resource(a, &target.role_arn, &target.region, account); match groups.iter_mut().find(|(res, _)| *res == r) { Some((_, v)) => v.push(a.to_string()), diff --git a/services/common/src/log_reader.rs b/services/common/src/log_reader.rs index 1667250c1..e2b824d53 100644 --- a/services/common/src/log_reader.rs +++ b/services/common/src/log_reader.rs @@ -40,6 +40,10 @@ pub struct Ability { pub name: &'static str, pub why: &'static str, pub actions: &'static [&'static str], + /// Granted only on what a team names (the knowledge bases it connects), + /// so the role's live check never counts it missing: connecting runs + /// its own test instead (`knowledge::remote::test_retrieve`). + pub chosen: bool, } /// Everything the current release's role allows, by ability. Tests keep @@ -59,18 +63,21 @@ pub const ABILITIES: &[Ability] = &[ "cloudwatch:DescribeAlarms", "sts:GetCallerIdentity", ], + chosen: false, }, Ability { key: "check", name: "Checking its own permissions", why: "Asks IAM which of these permissions the role has, and whether CoderHelm's own update stack finished, so this page can say when an update is needed. It only looks at this one role and CoderHelm's update stacks.", actions: &["iam:SimulatePrincipalPolicy", "cloudformation:DescribeStacks"], + chosen: false, }, Ability { key: "metrics", name: "CloudWatch metrics", why: "Reads error rate, latency and other metrics before and after a deploy.", actions: &["cloudwatch:GetMetricData", "cloudwatch:ListMetrics"], + chosen: false, }, Ability { key: "airflow", @@ -81,6 +88,7 @@ pub const ABILITIES: &[Ability] = &[ "airflow:GetEnvironment", "airflow:InvokeRestApi", ], + chosen: false, }, Ability { key: "ecs", @@ -94,6 +102,7 @@ pub const ABILITIES: &[Ability] = &[ "ecs:ListTasks", "ecs:DescribeTasks", ], + chosen: false, }, Ability { key: "code", @@ -106,6 +115,7 @@ pub const ABILITIES: &[Ability] = &[ "ecr:BatchGetImage", "ecr:ListTagsForResource", ], + chosen: false, }, Ability { key: "settings", @@ -118,6 +128,18 @@ pub const ABILITIES: &[Ability] = &[ "kms:DescribeKey", "kms:GetKeyPolicy", ], + chosen: false, + }, + Ability { + key: "knowledge", + name: "Bedrock knowledge bases", + why: "Searches the Bedrock knowledge bases a team connects, live and read-only, so answers can cite them; reads a cited document. Only the knowledge bases named in the stack's KnowledgeBases parameter (or every one in the account, when it says all). Nothing is copied out of the account and nothing is changed.", + actions: &[ + "bedrock:Retrieve", + "bedrock:GetDocumentContent", + "bedrock:ListKnowledgeBases", + ], + chosen: true, }, ]; @@ -134,6 +156,20 @@ pub fn all_actions() -> Vec<&'static str> { out } +/// The actions the role's live check asks about: every ability's except +/// the [`Ability::chosen`] ones, which only exist for what a team named. +pub fn checked_actions() -> Vec<&'static str> { + let mut out: Vec<&'static str> = Vec::new(); + for a in ABILITIES.iter().filter(|a| !a.chosen) { + for x in a.actions { + if !out.contains(x) { + out.push(x); + } + } + } + out +} + /// A short id of this release's set of permissions: changes exactly when an /// action is added or removed. pub fn permissions_id() -> String { @@ -271,12 +307,39 @@ pub fn quick_create_url( /// The one-click update: a Launch Stack link that adds this release's /// update stack to the role, in `region` (IAM is global; the region only -/// decides where the stack is listed). -pub fn update_url(update_template_url: &str, region: &str) -> String { - format!( +/// decides where the stack is listed). `knowledge_bases` are the ARNs of +/// the team's knowledge bases connected in this account: the stack lets the +/// role search them, and its name says which (a new set is a new stack, so +/// it never collides with the one before it). +pub fn update_url(update_template_url: &str, region: &str, knowledge_bases: &[String]) -> String { + let mut u = format!( "https://console.aws.amazon.com/cloudformation/home?region={region}#/stacks/quickcreate?stackName={}&templateURL={}¶m_RoleName={ROLE_NAME}", - update_stack_name(), + update_stack_name_for(knowledge_bases), urlencoding::encode(update_template_url) + ); + if !knowledge_bases.is_empty() { + u.push_str(&format!( + "¶m_KnowledgeBases={}", + urlencoding::encode(&knowledge_bases.join(",")) + )); + } + u +} + +/// This release's update stack name for a set of knowledge bases: the +/// release's own name when there are none. +pub fn update_stack_name_for(knowledge_bases: &[String]) -> String { + if knowledge_bases.is_empty() { + return update_stack_name(); + } + use sha2::{Digest, Sha256}; + let mut kbs: Vec<&str> = knowledge_bases.iter().map(String::as_str).collect(); + kbs.sort_unstable(); + kbs.dedup(); + format!( + "{}-kb{}", + update_stack_name(), + hex::encode(&Sha256::digest(kbs.join(",").as_bytes())[..3]) ) } @@ -337,6 +400,17 @@ mod tests { "{a} is not read-only" ); } + // Knowledge bases: search and read a cited document, only those named. + for t in [ROLE_TEMPLATE, UPDATE_TEMPLATE] { + assert!(t.contains("- Sid: ReadKnowledgeBases")); + assert!(t.contains("!Split [\",\", !Ref KnowledgeBases]")); + assert!(t.contains("knowledge-base/*")); + assert!(!t.contains("bedrock:Retrieve\"\n - \"bedrock:Rerank")); + assert!( + !template_actions(t).iter().any(|x| x.starts_with("bedrock:") + && !ability("knowledge").unwrap().actions.contains(&x.as_str())) + ); + } // Airflow's REST API only as the Viewer role. assert!(UPDATE_TEMPLATE.contains("arn:aws:airflow:*:*:role/*/Viewer")); assert!(ROLE_TEMPLATE.contains("arn:aws:airflow:*:*:role/*/Viewer")); @@ -353,6 +427,7 @@ mod tests { let u = update_url( "https://b.s3.amazonaws.com/launch/v1.2.3/coderhelm-log-reader-update.yaml", "eu-west-1", + &[], ); assert!(u.starts_with("https://console.aws.amazon.com/cloudformation/home?region=eu-west-1#/stacks/quickcreate?")); assert!(u.contains(&format!("stackName=CoderHelmLogReaderUpdate-{id}"))); @@ -428,6 +503,38 @@ mod tests { } } + #[test] + fn knowledge_bases_ride_on_the_update_and_are_never_counted_missing() { + let kb = "arn:aws:bedrock:us-east-1:111122223333:knowledge-base/ABCDE12345".to_string(); + let u = update_url( + "https://b/x/coderhelm-log-reader-update.yaml", + "us-east-1", + std::slice::from_ref(&kb), + ); + assert!(u.contains("¶m_KnowledgeBases=arn%3Aaws%3Abedrock%3Aus-east-1%3A111122223333%3Aknowledge-base%2FABCDE12345"), "{u}"); + let name = update_stack_name_for(std::slice::from_ref(&kb)); + assert!( + name.starts_with(&format!("{}-kb", update_stack_name())), + "{name}" + ); + assert!(name.len() <= 128); + assert!(u.contains(&format!("stackName={name}"))); + // The same set in another order is the same stack; another set is another. + let other = "arn:aws:bedrock:us-east-1:111122223333:knowledge-base/ZZZZZ00000".to_string(); + assert_eq!( + update_stack_name_for(&[kb.clone(), other.clone()]), + update_stack_name_for(&[other.clone(), kb.clone()]) + ); + assert_ne!(update_stack_name_for(&[kb.clone(), other]), name); + assert_eq!(update_stack_name_for(&[]), update_stack_name()); + assert!(!update_url("https://b/x/y.yaml", "us-east-1", &[]).contains("KnowledgeBases")); + // The live check asks about everything but the chosen knowledge bases. + let checked = checked_actions(); + assert!(!checked.contains(&"bedrock:Retrieve")); + assert!(checked.contains(&"logs:StartQuery")); + assert_eq!(checked.len() + 3, all_actions().len()); + } + #[test] fn missing_actions_follow_the_abilities() { assert!(missing_actions(&[]).is_empty()); diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index 868dda969..ace1cb4a3 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -691,12 +691,17 @@ async fn main() -> Result<(), Error> { "/knowledge", get(routes::knowledge::list_bases).post(routes::knowledge::create_base), ) + .route("/knowledge/bedrock", get(routes::knowledge::bedrock_bases)) .route( "/knowledge/:kb_id", get(routes::knowledge::get_base) .put(routes::knowledge::update_base) .delete(routes::knowledge::delete_base), ) + .route( + "/knowledge/:kb_id/check", + post(routes::knowledge::check_connection), + ) .route( "/knowledge/:kb_id/files", post(routes::knowledge::start_upload), diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index df44c6fff..5db5ad578 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -352,6 +352,8 @@ pub const CAPABILITIES: &[Capability] = &[ min_role: "admin", handlers: &[ "knowledge::create_base", + "knowledge::bedrock_bases", + "knowledge::check_connection", "knowledge::update_base", "knowledge::delete_base", "knowledge::start_upload", diff --git a/services/gateway/src/routes/brain.rs b/services/gateway/src/routes/brain.rs index a3011733e..b6fa0297d 100644 --- a/services/gateway/src/routes/brain.rs +++ b/services/gateway/src/routes/brain.rs @@ -1447,6 +1447,15 @@ fn graph_sources( } /// Runs one tool other than the code tools and registers what it read. +/// The connected knowledge bases that didn't answer, for the model to say +/// so instead of claiming they hold nothing. +fn unreached_note(unreached: &[common::knowledge::search::Unreached]) -> String { + unreached + .iter() + .map(|u| format!("\n(Couldn't search {} this time: {})", u.kb_name, u.reason)) + .collect() +} + /// Returns the text the model reads, a short summary for the dashboard, and /// whether it failed. async fn run_tool( @@ -1477,6 +1486,7 @@ async fn run_tool( match search( &st, &titan, + &super::knowledge::retriever(state, "brain"), &run.team_id, &run.kb_ids, q, @@ -1488,12 +1498,16 @@ async fn run_tool( Ok(found) if !found.hits.is_empty() => { super::knowledge::reembed(state, &run.team_id, &found.stale).await; let ids = reg.add_hits(&found.hits); - (reg.render(&ids), format!("{} passages", ids.len()), false) + ( + format!("{}{}", reg.render(&ids), unreached_note(&found.unreached)), + format!("{} passages", ids.len()), + false, + ) } Ok(found) => { super::knowledge::reembed(state, &run.team_id, &found.stale).await; ( - "No passages matched.".into(), + format!("No passages matched.{}", unreached_note(&found.unreached)), "No passages matched".into(), false, ) @@ -2248,6 +2262,7 @@ async fn answer( match search( &st, &titan, + &super::knowledge::retriever(state, "brain"), &run.team_id, &run.kb_ids, &retrieval_query(question, history), diff --git a/services/gateway/src/routes/connectors.rs b/services/gateway/src/routes/connectors.rs index d2225f1f2..102f01ef3 100644 --- a/services/gateway/src/routes/connectors.rs +++ b/services/gateway/src/routes/connectors.rs @@ -172,10 +172,12 @@ async fn log_reader( /// role up to this release's permissions (metrics, Airflow, ECS and the /// rest), as a stack in its own account, from the install's own template /// copy. None when the install's template has no update template next to -/// it (a template URL an operator chose). -pub fn update_stack_url(region: &str) -> Option { +/// it (a template URL an operator chose). `knowledge_bases` are the ARNs +/// of the team's knowledge bases connected in that account, which the +/// update lets the role search. +pub fn update_stack_url(region: &str, knowledge_bases: &[String]) -> Option { common::log_reader::update_template_url(&common::public_urls::log_reader_template_url()) - .map(|t| common::log_reader::update_url(&t, region)) + .map(|t| common::log_reader::update_url(&t, region, knowledge_bases)) } async fn record( @@ -858,7 +860,7 @@ pub async fn aws_check( { None } else { - update_stack_url(&t.region) + update_stack_url(&t.region, &[]) }, "stack_name": common::log_reader::update_stack_name(), "template_url": common::log_reader::update_template_url(&template), @@ -909,7 +911,7 @@ mod tests { #[test] fn the_update_link_opens_the_update_stack_for_the_existing_role() { - let u = update_stack_url("us-west-2").unwrap(); + let u = update_stack_url("us-west-2", &[]).unwrap(); assert!(u.starts_with("https://console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/quickcreate?")); assert!(u.contains("stackName=CoderHelmLogReaderUpdate-")); assert!(u.contains("coderhelm-log-reader-update.yaml")); diff --git a/services/gateway/src/routes/integrations.rs b/services/gateway/src/routes/integrations.rs index 8d9febf7f..ee08512c1 100644 --- a/services/gateway/src/routes/integrations.rs +++ b/services/gateway/src/routes/integrations.rs @@ -294,7 +294,7 @@ pub fn install_account(a: &AwsAccount) -> bool { /// person can add it (never in the install's own account). fn update_stack_link(a: &AwsAccount) -> Option { (!install_account(a) && (!aws_missing(a).is_empty() || needs_update(a))) - .then(|| super::connectors::update_stack_url(&a.region)) + .then(|| super::connectors::update_stack_url(&a.region, &a.knowledge_bases)) .flatten() } @@ -445,6 +445,7 @@ pub async fn list( aws_account::list(&state.dynamo, &state.config.aws_insights_table_name, &team) .await .map_err(|e| internal("list aws accounts", e))?; + with_knowledge_bases(&state, &team, &mut accounts).await; // A support view only reads: no migration, no checks into the team's // AWS accounts (they would run as the support admin). let support_view = claims.support_view.is_some(); @@ -576,7 +577,9 @@ pub async fn list( detail["missing"] = json!(aws_missing(a)); detail["update_url"] = json!(update_stack_link(a)); detail["install_account"] = json!(install_account(a)); - detail["stack_name"] = json!(common::log_reader::update_stack_name()); + detail["stack_name"] = json!(common::log_reader::update_stack_name_for( + &a.knowledge_bases + )); items.push(card( &format!("aws-{}", a.account), &format!("AWS account {}", a.account), @@ -787,6 +790,7 @@ async fn load_account( team_id: &str, account: &str, ) -> Result)> { + let kbs = common::knowledge::remote::arns_in(&team_bases(state, team_id).await, account); aws_account::list( &state.dynamo, &state.config.aws_insights_table_name, @@ -797,6 +801,27 @@ async fn load_account( .into_iter() .find(|a| a.account == account) .ok_or_else(|| fail(StatusCode::NOT_FOUND, "That AWS account isn't connected.")) + .map(|mut a| { + a.knowledge_bases = kbs; + a + }) +} + +/// Each account's connected knowledge bases, so its update link keeps the +/// role able to search them. +async fn with_knowledge_bases(state: &AppState, team_id: &str, accounts: &mut [AwsAccount]) { + let bases = team_bases(state, team_id).await; + for a in accounts { + a.knowledge_bases = common::knowledge::remote::arns_in(&bases, &a.account); + } +} + +async fn team_bases(state: &AppState, team_id: &str) -> Vec { + use common::knowledge::search::Store; + super::knowledge::store(state) + .bases(team_id) + .await + .unwrap_or_default() } fn account_reply(a: &AwsAccount) -> Value { @@ -804,7 +829,9 @@ fn account_reply(a: &AwsAccount) -> Value { detail["missing"] = json!(aws_missing(a)); detail["update_url"] = json!(update_stack_link(a)); detail["install_account"] = json!(install_account(a)); - detail["stack_name"] = json!(common::log_reader::update_stack_name()); + detail["stack_name"] = json!(common::log_reader::update_stack_name_for( + &a.knowledge_bases + )); let st = aws_state(a); json!({ "account": detail, "status": st.status, "reason": st.reason, "last_check": a.abilities.checked_at }) } diff --git a/services/gateway/src/routes/knowledge.rs b/services/gateway/src/routes/knowledge.rs index 8d8df2a14..c59a91dbe 100644 --- a/services/gateway/src/routes/knowledge.rs +++ b/services/gateway/src/routes/knowledge.rs @@ -48,6 +48,17 @@ fn forbidden(_: StatusCode) -> (StatusCode, Json) { fail(StatusCode::FORBIDDEN, "Only admins manage knowledge bases.") } +/// Searches the team's connected Bedrock knowledge bases, as `actor` in the +/// team's AWS records. +pub(crate) fn retriever<'a>(state: &'a AppState, actor: &'a str) -> kb::remote::Bedrock<'a> { + kb::remote::Bedrock { + sts: &state.sts, + dynamo: &state.dynamo, + accounts_table: &state.config.aws_insights_table_name, + actor, + } +} + pub(crate) fn store(state: &AppState) -> kb::search::AwsStore { kb::search::AwsStore { dynamo: state.dynamo.clone(), @@ -95,6 +106,21 @@ pub struct BaseInput { /// with what it holds in one step. #[serde(default)] pub source: Option, + /// On create only: a knowledge base to connect in place instead (it is + /// searched live where it is and holds no files here). + #[serde(default)] + pub connect: Option, +} + +/// A knowledge base to connect in place. +#[derive(Debug, Clone, Default, Deserialize)] +pub struct ConnectInput { + /// `bedrock_kb`. + #[serde(default)] + pub provider: String, + /// The Bedrock knowledge base's ARN. + #[serde(default)] + pub target: String, } /// `input` applied to `base`, or why it can't be. @@ -258,6 +284,7 @@ fn base_json( "authoritative": b.authoritative, "created_at": b.created_at, "updated_at": b.updated_at, + "backend": backend_json(b), "files": files.len(), "ready": count(FileStatus::Ready), "processing": count(FileStatus::Processing) + count(FileStatus::Uploading), @@ -265,6 +292,175 @@ fn base_json( }) } +/// Where a base's passages are, for the page: `local`, or connected in +/// place with where it lives and how it is reached (never a private ID). +fn backend_json(b: &Base) -> Value { + match b.remote() { + None => json!({ "kind": "local" }), + Some(r) => json!({ + "kind": "remote", + "provider": r.provider, + "label": r.provider.label(), + "target": r.target, + "region": r.region, + "account": r.target.split(':').nth(4).unwrap_or(""), + "access": match &r.access { + kb::Access::Install => "install", + kb::Access::Account { .. } => "account", + }, + "hybrid": r.hybrid, + }), + } +} + +/// Files and synced apps belong to bases kept here: a base connected in +/// place has none. +fn refuse_connected(base: &Base) -> Result<(), (StatusCode, Json)> { + match base.remote() { + Some(r) => Err(fail( + StatusCode::BAD_REQUEST, + &format!( + "This knowledge base is connected in place: it is searched live in your AWS account, so nothing can be added to it here. Add documents to the {} itself.", + r.provider.label() + ), + )), + None => Ok(()), + } +} + +/// Refuses adding to `kb_id` when it is connected in place. +pub(crate) async fn refuse_if_connected( + state: &AppState, + team_id: &str, + kb_id: &str, +) -> Result<(), (StatusCode, Json)> { + match get_base_record(state, team_id, kb_id) + .await + .map_err(|e| internal("knowledge base", e))? + { + Some(b) => refuse_connected(&b), + None => Ok(()), + } +} + +/// A connection failure as the page shows it: what happened, what to do, +/// and (when the role only lacks the permission) the one-click update that +/// grants it. +fn connect_fail(r: &kb::remote::Refusal, grant: Option) -> (StatusCode, Json) { + ( + StatusCode::BAD_REQUEST, + Json(json!({ + "error": r.message, + "fix": r.fix, + "code": r.code, + "grant": grant, + })), + ) +} + +/// The connected AWS accounts of the team (none when the install keeps no +/// such table). +async fn aws_accounts( + state: &AppState, + team_id: &str, +) -> Vec { + let table = &state.config.aws_insights_table_name; + if table.is_empty() { + return Vec::new(); + } + common::live::aws_account::list(&state.dynamo, table, team_id) + .await + .unwrap_or_else(|e| { + warn!(error = %e, "Could not read AWS accounts"); + Vec::new() + }) +} + +/// Checks a knowledge base to connect, with one test search, and returns +/// how it is reached. Nothing is saved. +async fn check_connect( + state: &AppState, + claims: &Claims, + existing: &[Base], + input: &ConnectInput, +) -> Result)> { + if !input.provider.is_empty() && input.provider != "bedrock_kb" { + return Err(fail( + StatusCode::BAD_REQUEST, + "Only a Bedrock knowledge base can be connected in place.", + )); + } + let arn = + kb::remote::parse_kb_arn(&input.target).map_err(|m| fail(StatusCode::BAD_REQUEST, &m))?; + if let Some(same) = existing + .iter() + .find(|b| b.remote().is_some_and(|r| r.target == arn.arn())) + { + return Err(fail( + StatusCode::BAD_REQUEST, + &format!("That knowledge base is already connected as {}.", same.name), + )); + } + let accounts = aws_accounts(state, &claims.team_id).await; + let own = common::live::aws::install_read_role(); + let access = kb::remote::access_for(&arn, own.as_deref(), &accounts) + .map_err(|r| connect_fail(&r, None))?; + let mut remote = kb::remote::bedrock_remote(&arn, access, true); + remote.hybrid = test_remote(state, claims, existing, &accounts, &remote).await?; + Ok(remote) +} + +/// One test search of `remote` as the team: `Ok(hybrid)`, or what went +/// wrong in plain words (with the one-click grant when the team's role only +/// lacks the permission). +async fn test_remote( + state: &AppState, + claims: &Claims, + existing: &[Base], + accounts: &[common::live::aws_account::AwsAccount], + remote: &kb::Remote, +) -> Result)> { + let actor = format!("knowledge-{}", claims.email); + let session = kb::remote::session( + &state.sts, + &state.dynamo, + &state.config.aws_insights_table_name, + &claims.team_id, + remote, + &actor, + ) + .await + .map_err(|r| connect_fail(&r, None))?; + kb::remote::test_retrieve(&session, remote).await.map_err(|r| { + // The team's role only lacks the permission: the update that lets + // it search this knowledge base (and the ones already connected in + // that account), in one click. + let grant = match (&remote.access, r.code) { + (kb::Access::Account { account }, "access") => { + let mut kbs = kb::remote::arns_in(existing, account); + kbs.push(remote.target.clone()); + kbs.sort(); + kbs.dedup(); + let region = accounts + .iter() + .find(|a| &a.account == account) + .map(|a| a.region.clone()) + .unwrap_or_else(|| remote.region.clone()); + super::connectors::update_stack_url(®ion, &kbs).map(|url| { + json!({ + "url": url, + "stack_name": common::log_reader::update_stack_name_for(&kbs), + "account": account, + }) + }) + } + _ => None, + }; + info!(team_id = %claims.team_id, code = r.code, "A connected knowledge base's test search failed"); + connect_fail(&r, grant) + }) +} + fn limits() -> Value { json!({ "max_file_bytes": MAX_FILE_BYTES, @@ -330,6 +526,80 @@ pub async fn get_base( // ── Managing (admins) ─────────────────────────────────────────────────────── +/// GET /api/knowledge/bedrock — what connecting a Bedrock knowledge base +/// starts from: on a self-hosted install, the knowledge bases in its own +/// account (or why they can't be listed); everywhere, the team's connected +/// AWS accounts, whose roles can search a pasted ARN. +pub async fn bedrock_bases( + State(state): State>, + Extension(claims): Extension, +) -> Reply { + claims.require_role(3).map_err(forbidden)?; + let own = common::live::aws::install_read_role(); + let region = std::env::var("AWS_REGION").unwrap_or_default(); + let (bases, list_error) = if own.is_some() && !region.is_empty() { + match kb::remote::list_install_bases(®ion).await { + Ok(b) => (Some(b), None), + Err(r) => ( + None, + Some(json!({ "message": r.message, "fix": r.fix, "code": r.code })), + ), + } + } else { + (None, None) + }; + let connected: Vec = store(&state) + .bases(&claims.team_id) + .await + .unwrap_or_default() + .iter() + .filter_map(|b| b.remote().map(|r| r.target.clone())) + .collect(); + let accounts: Vec = aws_accounts(&state, &claims.team_id) + .await + .iter() + .map(|a| json!({ "account": a.account, "region": a.region })) + .collect(); + Ok(Json(json!({ + "install": own.is_some(), + "install_account": own.as_deref().and_then(|r| r.split(':').nth(4)).unwrap_or(""), + "region": region, + "bases": bases, + "list_error": list_error, + "accounts": accounts, + "connected": connected, + }))) +} + +/// POST /api/knowledge/:kb_id/check — one test search of a connected base, +/// now: it works, or what is wrong and what to do. +pub async fn check_connection( + State(state): State>, + Extension(claims): Extension, + Path(kb_id): Path, +) -> Reply { + claims.require_role(3).map_err(forbidden)?; + let existing = store(&state) + .bases(&claims.team_id) + .await + .map_err(|e| internal("knowledge bases", e))?; + let base = existing + .iter() + .find(|b| b.id == kb_id) + .ok_or_else(|| fail(StatusCode::NOT_FOUND, "No such knowledge base."))?; + let remote = base.remote().ok_or_else(|| { + fail( + StatusCode::BAD_REQUEST, + "This knowledge base is kept here: there is no connection to check.", + ) + })?; + let accounts = aws_accounts(&state, &claims.team_id).await; + let hybrid = test_remote(&state, &claims, &existing, &accounts, remote).await?; + Ok(Json( + json!({ "ok": true, "hybrid": hybrid, "checked_at": now() }), + )) +} + /// POST /api/knowledge — create a base. pub async fn create_base( State(state): State>, @@ -356,6 +626,20 @@ pub async fn create_base( ..Default::default() }; apply_input(&mut base, &input).map_err(|m| fail(StatusCode::BAD_REQUEST, &m))?; + if let Some(c) = input + .connect + .as_ref() + .filter(|c| !c.target.trim().is_empty()) + { + if input.source.as_ref().is_some_and(|s| !s.kind.is_empty()) { + return Err(fail( + StatusCode::BAD_REQUEST, + "A knowledge base connected in place can't also sync an app.", + )); + } + // One test search first: nothing is saved unless it works. + base.backend = kb::Backend::Remote(check_connect(&state, &claims, &existing, c).await?); + } state .dynamo .put_item() @@ -364,7 +648,7 @@ pub async fn create_base( .send() .await .map_err(|e| internal("create knowledge base", e.to_string()))?; - info!(team_id = %claims.team_id, kb = %base.id, "Knowledge base created"); + info!(team_id = %claims.team_id, kb = %base.id, connected = base.remote().is_some(), "Knowledge base created"); let mut added = Value::Null; if let Some(src) = input.source.as_ref().filter(|s| !s.kind.is_empty()) { match super::knowledge_sources::add_source(&state, &claims, &base.id, src).await { @@ -554,6 +838,7 @@ pub async fn start_upload( .await .map_err(|e| internal("knowledge base", e))? .ok_or_else(|| fail(StatusCode::NOT_FOUND, "No such knowledge base."))?; + refuse_connected(&base)?; let name = kb::clean_file_name(&body.name); let kind = check_upload(&name, body.size, MAX_FILE_BYTES) .map_err(|m| fail(StatusCode::BAD_REQUEST, &m))?; @@ -850,4 +1135,65 @@ mod tests { .unwrap_err() .contains("25 MB")); } + + #[test] + fn a_connected_base_shows_where_it_lives_and_takes_no_files() { + let remote = kb::remote::bedrock_remote( + &kb::remote::parse_kb_arn( + "arn:aws:bedrock:eu-west-1:111122223333:knowledge-base/ABCDE12345", + ) + .unwrap(), + kb::Access::Account { + account: "111122223333".into(), + }, + false, + ); + let b = Base { + id: "kb".into(), + name: "Runbooks".into(), + backend: kb::Backend::Remote(remote), + ..Default::default() + }; + let v = base_json(&b, &[], &[]); + assert_eq!(v["backend"]["kind"], "remote"); + assert_eq!(v["backend"]["label"], "Bedrock knowledge base"); + assert_eq!(v["backend"]["region"], "eu-west-1"); + assert_eq!(v["backend"]["account"], "111122223333"); + assert_eq!(v["backend"]["access"], "account"); + assert_eq!(v["backend"]["hybrid"], false); + assert_eq!(v["files"], 0); + let (code, body) = refuse_connected(&b).unwrap_err(); + assert_eq!(code, StatusCode::BAD_REQUEST); + assert!(body["error"] + .as_str() + .unwrap() + .contains("connected in place")); + // A base kept here says so and takes files. + let local = Base::default(); + assert_eq!(base_json(&local, &[], &[])["backend"]["kind"], "local"); + assert!(refuse_connected(&local).is_ok()); + } + + #[test] + fn a_failed_connection_says_what_happened_what_to_do_and_offers_the_grant() { + let r = kb::remote::refusal("AccessDeniedException", "not authorized to perform: bedrock:Retrieve because no identity-based policy allows the bedrock:Retrieve action"); + let (code, body) = connect_fail( + &r, + Some(json!({ "url": "https://console.aws.amazon.com/x", "stack_name": "s" })), + ); + assert_eq!(code, StatusCode::BAD_REQUEST); + assert_eq!( + body["error"], + "The role in your account does not allow Retrieve on this knowledge base." + ); + assert_eq!(body["code"], "access"); + assert!(body["fix"].as_str().unwrap().contains("bedrock:Retrieve")); + assert_eq!(body["grant"]["stack_name"], "s"); + // The connect input reads as the dashboard sends it. + let input: BaseInput = serde_json::from_value(json!({ + "name": "Runbooks", "connect": { "provider": "bedrock_kb", "target": "arn:aws:bedrock:us-east-1:111122223333:knowledge-base/ABCDE12345" } + })) + .unwrap(); + assert_eq!(input.connect.unwrap().provider, "bedrock_kb"); + } } diff --git a/services/gateway/src/routes/knowledge_sources.rs b/services/gateway/src/routes/knowledge_sources.rs index fb8cdbd4e..c2edf2f62 100644 --- a/services/gateway/src/routes/knowledge_sources.rs +++ b/services/gateway/src/routes/knowledge_sources.rs @@ -713,6 +713,7 @@ pub(crate) async fn add_source( kb_id: &str, input: &SourceInput, ) -> Result)> { + super::knowledge::refuse_if_connected(state, &claims.team_id, kb_id).await?; let kind = kind_of(&input.kind)?; let selection = clean_selection(input.selection.as_deref().unwrap_or_default()) .map_err(|m| fail(StatusCode::BAD_REQUEST, &m))?; diff --git a/services/worker/src/passes/knowledge.rs b/services/worker/src/passes/knowledge.rs index bc61ba2e4..1bad9396c 100644 --- a/services/worker/src/passes/knowledge.rs +++ b/services/worker/src/passes/knowledge.rs @@ -367,9 +367,16 @@ impl KnowledgeTools { client: &state.bedrock, meter: &meter, }; + let retriever = common::knowledge::remote::Bedrock { + sts: &state.sts, + dynamo: &state.dynamo, + accounts_table: &state.config.aws_insights_table_name, + actor: "knowledge", + }; let hits = search( &store(state), &titan, + &retriever, &self.team_id, &ids, query, @@ -385,7 +392,14 @@ impl KnowledgeTools { "Knowledge files embedded by another model are skipped until re-embedded" ); } - render_hits(&found.hits) + let mut text = render_hits(&found.hits); + for u in &found.unreached { + text.push_str(&format!( + "\n(Couldn't search {} this time: {})", + u.kb_name, u.reason + )); + } + text } Err(e) => { warn!(error = %e, "Knowledge search failed");