Skip to content

Commit 3cdb081

Browse files
committed
Knowledge: connect a Bedrock knowledge base in place, searched live in the team's AWS account
A base can now be connected in place instead of copied: an Amazon Bedrock knowledge base, searched with bedrock-agent-runtime Retrieve each time it is needed. Nothing is copied: no documents, passages or vectors. - Base.backend: Local (every existing record, unchanged) or Remote with the provider, the knowledge base's ARN, the region from the ARN, and how it is reached (the install's own role, or the team's CoderHelmLogReader role in that account with the team's private ID). - A Retriever trait beside Store and Embedder, taking the team. search() splits bases by backend, asks every connected base at once, and fuses each one's ranked list with the local vector and keyword lists. The per-file cap uses the document id; the question is embedded only when a local file is searched. A base that doesn't answer is named; the others still answer. - The Bedrock retriever: HYBRID search where the store supports it (found by the test search), no reranking; text, document id, title or S3 key, a metadata date and the original link become the hit; SourceKind::BedrockKb. - Connecting runs one test search first; failures come back in plain words (the role does not allow Retrieve, the install's boundary, a resource policy, an SCP, no such knowledge base, an unreachable endpoint), with the one-click CoderHelmLogReader update when the role only lacks the grant. - ReadKnowledgeBases in both log reader templates, on a KnowledgeBases parameter (ARNs, or all); the install's own role gets every knowledge base in its own account through the same update template. - The boundary gains bedrock:Retrieve in today's boundary only: it reaches an install through the admin-applied access stack (access.json), never through an update; the pinned parent boundary is unchanged. - Docs: self-host knowledge sources.
1 parent 7a14dce commit 3cdb081

24 files changed

Lines changed: 2605 additions & 99 deletions

‎docs/self-host/knowledge-sources.md‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,40 @@ CoderHelm asks for `https://www.googleapis.com/auth/drive.readonly`. A knowledge
135135

136136
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.
137137

138+
## Bedrock knowledge bases, connected in place
139+
140+
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.
141+
142+
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:<region>:<account>:knowledge-base/<id>`). 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.
143+
144+
How it is searched:
145+
146+
- **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.
147+
- **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.
148+
- **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).
149+
- **The region is the ARN's.** A knowledge base in another region than the install is searched in its own region.
150+
- **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.
151+
152+
### Who searches it
153+
154+
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:*:<account>:knowledge-base/*`, and `bedrock:ListKnowledgeBases` for the list). Admins still choose which ones a team connects. Each version update brings this policy along.
155+
156+
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.
157+
158+
### The permissions boundary: one admin step
159+
160+
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).
161+
162+
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.
163+
164+
### Private networks
165+
166+
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.
167+
168+
### Who sees what
169+
170+
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.
171+
138172
## What runs
139173

140174
- **Schedule.** An EventBridge rule (`<prefix>-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.

‎infra/cfn/coderhelm-log-reader-update.yaml‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
AWSTemplateFormatVersion: "2010-09-09"
22
Description: >
33
Brings the existing CoderHelmLogReader role up to date with the read-only
4-
permissions the current CoderHelm release uses. Every permission here is
4+
permissions the current CoderHelm release uses, and lets it search the
5+
Bedrock knowledge bases named in KnowledgeBases. Every permission here is
56
read-only: CoderHelm can list, describe and query, never change anything.
67
It only adds: to drop a permission an older release granted, update the
78
CoderHelmLogReader stack itself with the current role template.
@@ -15,6 +16,20 @@ Parameters:
1516
Description: The CoderHelm role to update (do not change this value).
1617
AllowedPattern: "^CoderHelmLogReader$"
1718

19+
KnowledgeBases:
20+
Type: String
21+
Default: ""
22+
Description: >
23+
Bedrock knowledge bases CoderHelm may search, read-only: their ARNs
24+
separated by commas, or "all" for every knowledge base in this account.
25+
Empty: none (the role reads no knowledge base).
26+
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})*)$"
27+
ConstraintDescription: Knowledge base ARNs separated by commas, "all", or empty.
28+
29+
Conditions:
30+
ReadsKnowledgeBases: !Not [!Equals [!Ref KnowledgeBases, ""]]
31+
ReadsEveryKnowledgeBase: !Equals [!Ref KnowledgeBases, "all"]
32+
1833
Resources:
1934
CoderHelmReadOnlyUpdate:
2035
Type: AWS::IAM::Policy
@@ -104,3 +119,27 @@ Resources:
104119
- "kms:DescribeKey"
105120
- "kms:GetKeyPolicy"
106121
Resource: "*"
122+
# Bedrock knowledge bases connected in place: searched live in
123+
# this account, nothing copied. Only the knowledge bases named in
124+
# KnowledgeBases (or every one in this account with "all"):
125+
# search and read a cited document, never change one.
126+
- !If
127+
- ReadsKnowledgeBases
128+
- Sid: ReadKnowledgeBases
129+
Effect: Allow
130+
Action:
131+
- "bedrock:Retrieve"
132+
- "bedrock:GetDocumentContent"
133+
Resource: !If
134+
- ReadsEveryKnowledgeBase
135+
- !Sub "arn:aws:bedrock:*:${AWS::AccountId}:knowledge-base/*"
136+
- !Split [",", !Ref KnowledgeBases]
137+
- !Ref AWS::NoValue
138+
- !If
139+
- ReadsEveryKnowledgeBase
140+
- Sid: ListKnowledgeBases
141+
Effect: Allow
142+
Action:
143+
- "bedrock:ListKnowledgeBases"
144+
Resource: "*"
145+
- !Ref AWS::NoValue

‎infra/cfn/coderhelm-log-reader.yaml‎

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
AWSTemplateFormatVersion: "2010-09-09"
22
Description: >
3-
Creates a read-only IAM role that allows Coderhelm to query your CloudWatch Logs and metrics
4-
and read Airflow (MWAA) as a Viewer.
3+
Creates a read-only IAM role that allows Coderhelm to query your CloudWatch Logs and metrics,
4+
read Airflow (MWAA) as a Viewer, and search the Bedrock knowledge bases you name.
55
This role uses an External ID to prevent confused deputy attacks.
66
77
Parameters:
@@ -27,6 +27,20 @@ Parameters:
2727
allows any role in that account (do not change this value).
2828
AllowedPattern: "^[A-Za-z0-9_-]{0,41}$"
2929

30+
KnowledgeBases:
31+
Type: String
32+
Default: ""
33+
Description: >
34+
Bedrock knowledge bases CoderHelm may search, read-only: their ARNs
35+
separated by commas, or "all" for every knowledge base in this account.
36+
Empty: none (the role reads no knowledge base).
37+
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})*)$"
38+
ConstraintDescription: Knowledge base ARNs separated by commas, "all", or empty.
39+
40+
Conditions:
41+
ReadsKnowledgeBases: !Not [!Equals [!Ref KnowledgeBases, ""]]
42+
ReadsEveryKnowledgeBase: !Equals [!Ref KnowledgeBases, "all"]
43+
3044
Resources:
3145
CoderHelmLogReaderRole:
3246
Type: AWS::IAM::Role
@@ -172,6 +186,34 @@ Resources:
172186
- "kms:DescribeKey"
173187
- "kms:GetKeyPolicy"
174188
Resource: "*"
189+
# Bedrock knowledge bases connected in place: searched live in this
190+
# account, nothing copied. Only the knowledge bases named in
191+
# KnowledgeBases (or every one in this account with "all"): search
192+
# and read a cited document, never change one.
193+
- !If
194+
- ReadsKnowledgeBases
195+
- PolicyName: KnowledgeBasesReadOnly
196+
PolicyDocument:
197+
Version: "2012-10-17"
198+
Statement:
199+
- Sid: ReadKnowledgeBases
200+
Effect: Allow
201+
Action:
202+
- "bedrock:Retrieve"
203+
- "bedrock:GetDocumentContent"
204+
Resource: !If
205+
- ReadsEveryKnowledgeBase
206+
- !Sub "arn:aws:bedrock:*:${AWS::AccountId}:knowledge-base/*"
207+
- !Split [",", !Ref KnowledgeBases]
208+
- !If
209+
- ReadsEveryKnowledgeBase
210+
- Sid: ListKnowledgeBases
211+
Effect: Allow
212+
Action:
213+
- "bedrock:ListKnowledgeBases"
214+
Resource: "*"
215+
- !Ref AWS::NoValue
216+
- !Ref AWS::NoValue
175217

176218
Outputs:
177219
RoleArn:

‎infra/lib/access.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,13 @@ export const BOUNDARY_SERVICES = [
212212
"bedrock:InvokeModelWithResponseStream",
213213
"bedrock:Get*",
214214
"bedrock:List*",
215+
// Searching a Bedrock knowledge base connected in place, in the install's own
216+
// account (own-account-read.ts; GetDocumentContent and ListKnowledgeBases are
217+
// under Get* and List*). It reaches an install only through the access stack
218+
// an AWS admin applies (native/access-stack.ts): the parent keeps its pinned
219+
// boundary (access-pinned.json), and until the admin step the knowledge base
220+
// page says so (services/common/src/knowledge/remote.rs, refusal).
221+
"bedrock:Retrieve",
215222
"cloudformation:*",
216223
"cloudfront:*",
217224
"cloudwatch:*",

‎infra/lib/own-account-read.ts‎

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,13 @@
1212
* Connecting the account still proves the team's own CoderHelmLogReader role
1313
* with its private ID (routes/log_analyzer.rs); only reading uses the
1414
* install's role (services/common/src/live/aws.rs, install_target).
15+
*
16+
* Bedrock knowledge bases connected in place (services/common/src/knowledge/remote.rs):
17+
* the install is the customer's alone, so its role may search every knowledge
18+
* base in its own account (the template's KnowledgeBases "all"), and list them
19+
* for the picker. Admins still choose which ones a team connects. Retrieve also
20+
* needs the permissions boundary to allow bedrock:Retrieve, which reaches an
21+
* install only through the access stack an AWS admin applies (native/access-stack.ts).
1522
*/
1623
import * as cdk from "aws-cdk-lib";
1724
import * as iam from "aws-cdk-lib/aws-iam";
@@ -24,15 +31,39 @@ export const OWN_ROLE_ENV = "INSTALL_OWN_ROLE_ARN";
2431
const UPDATE_TEMPLATE = "infra/cfn/coderhelm-log-reader-update.yaml";
2532
const UPDATE_POLICY_ID = "CoderHelmReadOnlyUpdate";
2633
const ROLE_NAME_MARK = "__CODERHELM_ROLE__";
34+
/** The install's own role searches every knowledge base in its own account. */
35+
const OWN_KNOWLEDGE_BASES = "all";
36+
/** The template's conditions for that value. A condition not listed here fails the build. */
37+
const OWN_CONDITIONS: Record<string, boolean> = { ReadsKnowledgeBases: true, ReadsEveryKnowledgeBase: true };
2738

2839
type Statement = { Sid?: string; Effect: string; Action: string | string[]; Resource: unknown };
2940

30-
/** The update template's statements, as the template has them. */
41+
/**
42+
* `v` with every `Fn::If` decided by `conditions` and every `AWS::NoValue`
43+
* dropped, as CloudFormation would for those values (CfnInclude keeps them,
44+
* and the policy is written into another stack that has no such conditions).
45+
*/
46+
export function decideConditions(v: unknown, conditions: Record<string, boolean>): unknown {
47+
const noValue = (x: unknown) => !!x && typeof x === "object" && (x as any).Ref === "AWS::NoValue";
48+
if (Array.isArray(v)) return v.map((x) => decideConditions(x, conditions)).filter((x) => !noValue(x));
49+
if (v && typeof v === "object") {
50+
const o = v as Record<string, unknown>;
51+
if (Object.keys(o).length === 1 && Array.isArray(o["Fn::If"])) {
52+
const [name, yes, no] = o["Fn::If"] as [string, unknown, unknown];
53+
if (!(name in conditions)) throw new Error(`${UPDATE_TEMPLATE}: condition ${name} isn't decided for the install's own role (own-account-read.ts)`);
54+
return decideConditions(conditions[name] ? yes : no, conditions);
55+
}
56+
return Object.fromEntries(Object.entries(o).map(([k, x]) => [k, decideConditions(x, conditions)]).filter(([, x]) => !noValue(x)));
57+
}
58+
return v;
59+
}
60+
61+
/** The update template's statements for the install's own role: its knowledge bases are every one in its account. */
3162
export function updateTemplateStatements(): Statement[] {
3263
const scratch = new cdk.Stack(new cdk.App(), "Scratch");
33-
const inc = new CfnInclude(scratch, "T", { templateFile: repoPath(UPDATE_TEMPLATE), parameters: { RoleName: ROLE_NAME_MARK } });
64+
const inc = new CfnInclude(scratch, "T", { templateFile: repoPath(UPDATE_TEMPLATE), parameters: { RoleName: ROLE_NAME_MARK, KnowledgeBases: OWN_KNOWLEDGE_BASES } });
3465
const p = inc.getResource(UPDATE_POLICY_ID) as iam.CfnPolicy;
35-
return scratch.resolve(p.policyDocument).Statement as Statement[];
66+
return decideConditions(scratch.resolve(p.policyDocument).Statement, OWN_CONDITIONS) as Statement[];
3667
}
3768

3869
/**
@@ -49,7 +80,7 @@ export function ownAccountStatements(roleArn: string): Statement[] {
4980
export function grantOwnAccountRead(scope: Construct, id: string, fn: cdk.aws_lambda.Function): void {
5081
const role = fn.role!;
5182
new iam.CfnManagedPolicy(scope, id, {
52-
description: "CoderHelm: reads this install's own AWS account (logs, metrics, Airflow, ECS), read-only; kept current by each version update",
83+
description: "CoderHelm: reads this install's own AWS account (logs, metrics, Airflow, ECS, Bedrock knowledge bases), read-only; kept current by each version update",
5384
roles: [role.roleName],
5485
policyDocument: { Version: "2012-10-17", Statement: ownAccountStatements(role.roleArn) },
5586
});

‎infra/test/fixtures/native-sim.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -489,6 +489,7 @@
489489
"bedrock:InvokeModelWithResponseStream",
490490
"bedrock:Get*",
491491
"bedrock:List*",
492+
"bedrock:Retrieve",
492493
"cloudformation:*",
493494
"cloudfront:*",
494495
"cloudwatch:*",

‎infra/test/native-access.test.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,14 +52,16 @@ const canon = (v: unknown) => JSON.stringify(v, (_k, x) => (x && typeof x === "o
5252
const sha = (v: unknown) => crypto.createHash("sha256").update(canon(v)).digest("hex");
5353

5454
/**
55-
* Today's boundary and deploy role policy, as their sha256. A change here
55+
* Today's boundary and deploy role policy, as their sha256. Last changed for
56+
* bedrock:Retrieve (a Bedrock knowledge base connected in place, searched with
57+
* the install's own role). A change here
5658
* reaches no install by itself: an AWS admin applies it through the access
5759
* stack (Settings, System, Permissions). Before changing these two values,
5860
* batch it with whatever else needs the same admin step, and say so in the
5961
* release notes; the dashboard then offers it as one optional item.
6062
*/
6163
const ACCESS_DOCS = {
62-
boundary: "e336aa5d3446090ae84ae7b36ab55953455d662b997ab0947aabb5a091ec555e",
64+
boundary: "1dfff5e344b055bba2eb45e611d86466018eff191525cbbffab7fdf33b841141",
6365
deployRole: "d11f40637e639812ba5408d153351341bc593cb604726f6cb4193861c2dd7b1f",
6466
};
6567

@@ -158,3 +160,19 @@ test("the access stack has no service role and changes nothing on delete", () =>
158160
for (const r of Object.values<any>(ACCESS.Resources)) assert.equal(r.DeletionPolicy, undefined);
159161
assert.match(fs.readFileSync(path.join(__dirname, "..", "..", "..", "lambda", "native-access", "handler.py"), "utf8"), /On Delete it changes nothing/);
160162
});
163+
164+
test("searching a connected Bedrock knowledge base arrives with the access stack, never with an update", () => {
165+
const values = prodValues("111122223333", "us-east-1");
166+
const kb = { action: "bedrock:Retrieve", resource: "arn:aws:bedrock:us-east-1:111122223333:knowledge-base/ABCDE12345" };
167+
const anything: PolicyDocument = { Version: "2012-10-17", Statement: [{ Sid: "All", Effect: "Allow", Action: "*", Resource: "*" }] };
168+
// The parent's boundary is the pinned one: an update leaves an install without Retrieve.
169+
const pinned = resolveValue((pinnedAccess().Boundary as any).Properties.PolicyDocument, { values, conditions: { HasEmailFrom: true } }) as PolicyDocument;
170+
assert.notEqual(decision([anything], pinned, kb), "allowed", "the pinned boundary must not change");
171+
// Today's boundary, which access.json writes when an AWS admin applies it, allows it.
172+
const today = resolveValue(ACCESS.Resources.Access.Properties.Boundary.Document, { values: { ...values, EmailFrom: "owner@example.org" }, conditions: { HasEmailFrom: true } }) as PolicyDocument;
173+
assert.equal(decision([anything], today, kb), "allowed");
174+
// Listing and reading a cited document were already allowed (bedrock:List*, bedrock:Get*).
175+
for (const action of ["bedrock:ListKnowledgeBases", "bedrock:GetDocumentContent"]) {
176+
assert.equal(decision([anything], pinned, { ...kb, action }), "allowed", action);
177+
}
178+
});

‎infra/test/synth.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ test("self-host: the gateway and worker read the install's own account with this
195195
for (const a of needed) assert.ok(doc.includes(`"${a}"`), `${fn} lacks ${a}`);
196196
// Only reads: list, describe, get, query, never a write.
197197
const actions: string[] = policies[0].Properties.PolicyDocument.Statement.flatMap((s: any) => ([] as string[]).concat(s.Action));
198-
for (const a of actions) assert.match(a, /^[a-z0-9-]+:(List|Describe|Get|Filter|Start(Query)?$|Stop(Query)?$|BatchGet|Simulate|InvokeRestApi)/, a);
198+
for (const a of actions) assert.match(a, /^[a-z0-9-]+:(List|Describe|Get|Filter|Start(Query)?$|Stop(Query)?$|BatchGet|Simulate|InvokeRestApi|Retrieve$)/, a);
199199
// It checks its own permissions on its own role only.
200200
const sim = policies[0].Properties.PolicyDocument.Statement.find((s: any) => ([] as string[]).concat(s.Action).includes("iam:SimulatePrincipalPolicy"));
201201
assert.ok(JSON.stringify(sim.Resource).includes("Fn::GetAtt"), "its own role's ARN");

0 commit comments

Comments
 (0)