Skip to content

Feat: Add executionId and client IP to function headers #9147

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: 1.7.x
Choose a base branch
from

Conversation

JoshiJoshiJoshi
Copy link

@JoshiJoshiJoshi JoshiJoshiJoshi commented Dec 30, 2024

What does this PR do?

This PR adds the executionId and the client IP to the function headers so that they are accessible within the function execution.

Fixes #9316

Test Plan

Manual testing (see screenshots)
CleanShot 2024-12-30 at 18 49 22@2x
CleanShot 2024-12-30 at 18 53 02@2x
CleanShot 2024-12-30 at 18 57 49@2x
image
CleanShot 2024-12-30 at 19 11 40@2x

Related PRs and Issues

Checklist

  • If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs?

Copy link

github-actions bot commented Dec 30, 2024

Security Scan Results for PR

Docker Image Scan Results

Package Version Vulnerability Severity
binutils 2.42-r0 CVE-2025-0840 HIGH
git 2.45.3-r0 CVE-2025-46334 HIGH
git 2.45.3-r0 CVE-2025-48384 HIGH
git 2.45.3-r0 CVE-2025-48385 HIGH
git-init-template 2.45.3-r0 CVE-2025-46334 HIGH
git-init-template 2.45.3-r0 CVE-2025-48384 HIGH
git-init-template 2.45.3-r0 CVE-2025-48385 HIGH
icu 74.2-r0 CVE-2025-5222 HIGH
icu-data-en 74.2-r0 CVE-2025-5222 HIGH
icu-dev 74.2-r0 CVE-2025-5222 HIGH
icu-libs 74.2-r0 CVE-2025-5222 HIGH
libecpg 16.8-r0 CVE-2025-8714 HIGH
libecpg 16.8-r0 CVE-2025-8715 HIGH
libecpg-dev 16.8-r0 CVE-2025-8714 HIGH
libecpg-dev 16.8-r0 CVE-2025-8715 HIGH
libexpat 2.6.4-r0 CVE-2024-8176 HIGH
libpq 16.8-r0 CVE-2025-8714 HIGH
libpq 16.8-r0 CVE-2025-8715 HIGH
libpq-dev 16.8-r0 CVE-2025-8714 HIGH
libpq-dev 16.8-r0 CVE-2025-8715 HIGH
libxml2 2.12.7-r0 CVE-2024-56171 HIGH
libxml2 2.12.7-r0 CVE-2025-24928 HIGH
libxml2 2.12.7-r0 CVE-2025-27113 HIGH
libxml2 2.12.7-r0 CVE-2025-32414 HIGH
libxml2 2.12.7-r0 CVE-2025-32415 HIGH
postgresql16-dev 16.8-r0 CVE-2025-8714 HIGH
postgresql16-dev 16.8-r0 CVE-2025-8715 HIGH
pyc 3.12.9-r0 CVE-2024-12718 HIGH
pyc 3.12.9-r0 CVE-2025-4138 HIGH
pyc 3.12.9-r0 CVE-2025-4330 HIGH
pyc 3.12.9-r0 CVE-2025-4517 HIGH
python3 3.12.9-r0 CVE-2024-12718 HIGH
python3 3.12.9-r0 CVE-2025-4138 HIGH
python3 3.12.9-r0 CVE-2025-4330 HIGH
python3 3.12.9-r0 CVE-2025-4517 HIGH
python3-pyc 3.12.9-r0 CVE-2024-12718 HIGH
python3-pyc 3.12.9-r0 CVE-2025-4138 HIGH
python3-pyc 3.12.9-r0 CVE-2025-4330 HIGH
python3-pyc 3.12.9-r0 CVE-2025-4517 HIGH
python3-pycache-pyc0 3.12.9-r0 CVE-2024-12718 HIGH
python3-pycache-pyc0 3.12.9-r0 CVE-2025-4138 HIGH
python3-pycache-pyc0 3.12.9-r0 CVE-2025-4330 HIGH
python3-pycache-pyc0 3.12.9-r0 CVE-2025-4517 HIGH
sqlite-libs 3.45.3-r1 CVE-2025-29087 HIGH
xz 5.6.2-r0 CVE-2025-31115 HIGH
xz-libs 5.6.2-r0 CVE-2025-31115 HIGH
golang.org/x/crypto v0.31.0 CVE-2025-22869 HIGH
golang.org/x/oauth2 v0.24.0 CVE-2025-22868 HIGH
stdlib 1.22.10 CVE-2025-47907 HIGH

Source Code Scan Results

🎉 No vulnerabilities found!

@JoshiJoshiJoshi
Copy link
Author

JoshiJoshiJoshi commented Dec 30, 2024

Unsure how to proceed with the following lines:

// V2 vars
if ($version === 'v2') {
$vars = \array_merge($vars, [
'APPWRITE_FUNCTION_TRIGGER' => $headers['x-appwrite-trigger'] ?? '',
'APPWRITE_FUNCTION_DATA' => $body ?? '',
'APPWRITE_FUNCTION_USER_ID' => $headers['x-appwrite-user-id'] ?? '',
'APPWRITE_FUNCTION_JWT' => $headers['x-appwrite-user-jwt'] ?? ''
]);
}

// V2 vars
if ($version === 'v2') {
$vars = \array_merge($vars, [
'APPWRITE_FUNCTION_TRIGGER' => $headers['x-appwrite-trigger'] ?? '',
'APPWRITE_FUNCTION_DATA' => $body ?? '',
'APPWRITE_FUNCTION_USER_ID' => $headers['x-appwrite-user-id'] ?? '',
'APPWRITE_FUNCTION_JWT' => $headers['x-appwrite-user-jwt'] ?? ''
]);
}

Should they be added to v2 runtimes as well?

@Meldiron
Copy link
Contributor

Meldiron commented Jan 5, 2025

Unsure how to proceed with the following lines:
Should they be added to v2 runtimes as well?

V2 is backwards compatibility for older functions syntax. It's for when functions used to get req, res instead of context. V2 functions don't allow new build, and support only exists to keep supporting existing functions.

No need to implement any of the new features into v2 statements

@@ -12,6 +12,8 @@ func main(req: RequestValue, res: RequestResponse) throws -> RequestResponse {
"APPWRITE_FUNCTION_USER_ID": req.variables["APPWRITE_FUNCTION_USER_ID"],
"APPWRITE_FUNCTION_JWT": req.variables["APPWRITE_FUNCTION_JWT"],
"APPWRITE_FUNCTION_PROJECT_ID": req.variables["APPWRITE_FUNCTION_PROJECT_ID"],
"APPWRITE_FUNCTION_EXECUTION_ID": req.variables["APPWRITE_FUNCTION_EXECUTION_ID"],
"APPWRITE_FUNCTION_CLIENT_IP": req.variables["APPWRITE_FUNCTION_CLIENT_IP"],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Amazing job updating tests too 🔥
Let's also update test themselves in FunctionsCustomClientTest.php and FunctionsCustomServerTest.php. You can look for tests for APPWRITE_FUNCTION_USER_ID, and in those places, add test for APPWRITE_FUNCTION_EXECUTION_ID and APPWRITE_FUNCTION_CLIENT_IP.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added tests, eventho rather basic ones. If you need them to be more extensive just give me a heads up.

@JoshiJoshiJoshi
Copy link
Author

Can we consider adding x-appwrite-user-session-id as well as

x-appwrite-client-locale ("X-Appwrite-Locale")
x-appwrite-client-user-agent ("user-agent")
x-appwrite-client-origin ("origin")

too?

@stnguyen90 stnguyen90 linked an issue Feb 12, 2025 that may be closed by this pull request
2 tasks
@Hanibachi
Copy link

Cannot wait for this to be implemented

@watzon
Copy link

watzon commented Mar 25, 2025

Any movement on this? I need a way to get the execution id from within my function call.

@vermakhushboo vermakhushboo force-pushed the feat-extend-function-headers branch from 1948f27 to 0243517 Compare August 22, 2025 05:57
Copy link
Contributor

coderabbitai bot commented Aug 22, 2025

📝 Walkthrough

Walkthrough

Generates a single execution identifier earlier in request handling and reuses it for the persisted execution Document and the x-appwrite-execution-id response header. Adds an x-appwrite-client-ip header populated from the request IP across controller, module, and worker flows. Removes duplicate later-generation of execution IDs. Updates end-to-end tests to assert the execution ID header is exposed and that a client IP header is present. Updates the sample function to return APPWRITE_FUNCTION_EXECUTION_ID and APPWRITE_FUNCTION_CLIENT_IP in its JSON response and coerces the status code to a number.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Assessment against linked issues

Objective Addressed Explanation
Expose execution ID in function execution via header (#9316)

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Add and propagate x-appwrite-client-ip header (app/controllers/general.php) Client IP header was not requested by issue #9316.
Add and propagate x-appwrite-client-ip header (src/Appwrite/Platform/Modules/Functions/Http/Executions/Create.php) Client IP header addition is beyond the stated objective of exposing execution ID.
Add and propagate x-appwrite-client-ip header in workers (src/Appwrite/Platform/Workers/Functions.php) Client IP propagation in fail/execute flows is not in the linked issue scope.
tests/resources/functions/basic/index.js: include APPWRITE_FUNCTION_CLIENT_IP and coerce statusCode to number Adding client IP to function output and status code coercion are unrelated to exposing the execution ID header.

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 0a5139c and af3d585.

📒 Files selected for processing (1)
  • tests/e2e/Services/Functions/FunctionsCustomServerTest.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/e2e/Services/Functions/FunctionsCustomServerTest.php
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (17)
  • GitHub Check: E2E Service Test (VCS)
  • GitHub Check: E2E Service Test (Tokens)
  • GitHub Check: E2E Service Test (Proxy)
  • GitHub Check: E2E Service Test (Avatars)
  • GitHub Check: E2E Service Test (GraphQL)
  • GitHub Check: E2E Service Test (Health)
  • GitHub Check: E2E Service Test (Locale)
  • GitHub Check: E2E Service Test (Functions)
  • GitHub Check: E2E Service Test (FunctionsSchedule)
  • GitHub Check: E2E Service Test (Console)
  • GitHub Check: E2E Service Test (Account)
  • GitHub Check: E2E Service Test (Dev Keys)
  • GitHub Check: E2E Service Test (Site Screenshots)
  • GitHub Check: Unit Test
  • GitHub Check: E2E General Test
  • GitHub Check: Benchmark
  • GitHub Check: scan
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vermakhushboo vermakhushboo changed the base branch from 1.6.x to 1.7.x August 22, 2025 05:57
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/Appwrite/Platform/Modules/Functions/Http/Executions/Create.php (1)

248-255: Ensure the request header allowlist includes execution and client IP headers

The constant FUNCTION_ALLOWLIST_HEADERS_REQUEST (defined in app/init/constants.php at line 149) currently only whitelists the following headers:

const FUNCTION_ALLOWLIST_HEADERS_REQUEST = [
    'content-type',
    'agent',
    'content-length',
    'host'
];

You need to add both x-appwrite-execution-id and x-appwrite-client-ip so that these headers aren’t dropped when persisting the execution’s requestHeaders. For example:

 app/init/constants.php
@@ -147,5 +147,8 @@
 // Function headers
-const FUNCTION_ALLOWLIST_HEADERS_REQUEST = ['content-type', 'agent', 'content-length', 'host'];
+const FUNCTION_ALLOWLIST_HEADERS_REQUEST = [
+    'content-type',
+    'agent',
+    'content-length',
+    'host',
+    'x-appwrite-execution-id',
+    'x-appwrite-client-ip',
+];

 const FUNCTION_ALLOWLIST_HEADERS_RESPONSE = ['content-type', 'content-length'];

– Without these additions, observability tools cannot read the execution ID or client IP from the stored execution document.

♻️ Duplicate comments (2)
app/controllers/general.php (1)

359-365: Naming settled; “client” namespace aligns with earlier discussion.

  • Using x-appwrite-client-ip is consistent with the prior decision to use “client” for internet clients and to avoid implying authenticated users. No further action needed.
src/Appwrite/Platform/Workers/Functions.php (1)

402-412: Don’t clobber upstream client IP; optionally adopt header executionId when param is missing

  • If controllers already populated x-appwrite-client-ip, this unconditionally overwrites it with an empty string, losing information. Set it only when it’s absent.
  • For event/schedule paths where $executionId may be null/empty, consider adopting an upstream x-appwrite-execution-id header if present to preserve single-source execution ID across the pipeline.
  • Header names LGTM and align with prior discussion.

Apply:

-        $headers['x-appwrite-execution-id'] = $executionId ?? '';
+        // Prefer provided executionId; if missing, adopt one from headers (e.g., controllers)
+        if (empty($executionId) && !empty($headers['x-appwrite-execution-id'])) {
+            $executionId = $headers['x-appwrite-execution-id'];
+        }
+        $headers['x-appwrite-execution-id'] = $executionId ?? '';

         $headers['x-appwrite-key'] = API_KEY_DYNAMIC . '_' . $apiKey;
         $headers['x-appwrite-trigger'] = $trigger;
         $headers['x-appwrite-event'] = $event ?? '';
         $headers['x-appwrite-user-id'] = $user->getId() ?? '';
         $headers['x-appwrite-user-jwt'] = $jwt ?? '';
         $headers['x-appwrite-country-code'] = '';
         $headers['x-appwrite-continent-code'] = '';
         $headers['x-appwrite-continent-eu'] = 'false';
-        $headers['x-appwrite-client-ip'] = '';
+        // Do not overwrite IP if controller already set it; default to empty string otherwise
+        $headers['x-appwrite-client-ip'] = $headers['x-appwrite-client-ip'] ?? ($headers['x-forwarded-for'] ?? '');
🧹 Nitpick comments (3)
app/controllers/general.php (1)

377-388: Prefer robust client-IP resolution for geolocation.

  • You currently geolocate by x-real-ip only. In environments where that header isn’t present, you’ll miss geodata while still sending x-appwrite-client-ip from Request::getIP().
  • Optional: fall back to $request->getIP() (or first IP from X-Forwarded-For) when x-real-ip is empty, so geodata remains consistent with the client IP you expose to functions.

Example (outside the changed range, for illustration only):

$ip = $headers['x-real-ip'] ?? '';
if (empty($ip)) {
    $xff = $headers['x-forwarded-for'] ?? '';
    $ip = $xff ? \trim(\explode(',', $xff)[0]) : $request->getIP();
}
src/Appwrite/Platform/Modules/Functions/Http/Executions/Create.php (1)

224-226: Add test coverage for header override protection.

  • We already test non-override for several headers, but not for x-appwrite-execution-id. Consider extending tests to assert that user-supplied x-appwrite-execution-id is ignored/overridden.

Proposed addition (tests/e2e/Services/Functions/FunctionsCustomClientTest.php, method testNonOverrideOfHeaders):

         $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', array_merge([
             'content-type' => 'application/json',
             'x-appwrite-project' => $this->getProject()['$id'],
         ], $this->getHeaders()), [
             'x-appwrite-event' => "OVERRIDDEN",
             'x-appwrite-trigger' => "OVERRIDDEN",
             'x-appwrite-user-id' => "OVERRIDDEN",
             'x-appwrite-user-jwt' => "OVERRIDDEN",
+            'x-appwrite-execution-id' => "OVERRIDDEN",
+            'x-appwrite-client-ip' => "255.255.255.255",
         ]);
 
         $output = json_decode($execution['body']['responseBody'], true);
         $this->assertNotEquals('OVERRIDDEN', $output['APPWRITE_FUNCTION_JWT']);
         $this->assertNotEquals('OVERRIDDEN', $output['APPWRITE_FUNCTION_EVENT']);
         $this->assertNotEquals('OVERRIDDEN', $output['APPWRITE_FUNCTION_TRIGGER']);
         $this->assertNotEquals('OVERRIDDEN', $output['APPWRITE_FUNCTION_USER_ID']);
+        $this->assertNotEquals('OVERRIDDEN', $output['APPWRITE_FUNCTION_EXECUTION_ID']);
+        $this->assertNotEquals('255.255.255.255', $output['APPWRITE_FUNCTION_CLIENT_IP']);
tests/e2e/Services/Functions/FunctionsCustomClientTest.php (1)

162-166: Great assertions for execution ID and client IP.

  • Verifying APPWRITE_FUNCTION_EXECUTION_ID matches the execution document ID and that APPWRITE_FUNCTION_CLIENT_IP is non-empty gives strong end-to-end coverage.

Optional: Also assert the ID format (e.g., not empty and matches your ID charset/length) to catch regressions in ID generation.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d68e394 and a4fbf3a.

📒 Files selected for processing (6)
  • app/controllers/general.php (1 hunks)
  • src/Appwrite/Platform/Modules/Functions/Http/Executions/Create.php (1 hunks)
  • src/Appwrite/Platform/Workers/Functions.php (3 hunks)
  • tests/e2e/Services/Functions/FunctionsCustomClientTest.php (1 hunks)
  • tests/e2e/Services/Functions/FunctionsCustomServerTest.php (1 hunks)
  • tests/resources/functions/basic/index.js (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
src/Appwrite/Platform/Modules/Functions/Http/Executions/Create.php (1)
src/Appwrite/Event/Audit.php (1)
  • getIP (113-116)
app/controllers/general.php (1)
src/Appwrite/Event/Audit.php (1)
  • getIP (113-116)
tests/e2e/Services/Functions/FunctionsCustomClientTest.php (1)
src/Appwrite/Utopia/Response.php (1)
  • output (658-740)
🔇 Additional comments (5)
app/controllers/general.php (1)

359-361: Single-source executionId propagation looks correct.

  • Generating the executionId once and reusing it for both the header and the execution document mitigates correlation bugs and simplifies tracing. Good call.
src/Appwrite/Platform/Modules/Functions/Http/Executions/Create.php (1)

224-226: Good: single executionId + client IP propagated into function context.

  • Creating executionId once and overriding any inbound x-appwrite-execution-id prevents spoofing. Setting x-appwrite-client-ip from Request::getIP() is appropriate.

Also applies to: 233-234

tests/resources/functions/basic/index.js (1)

44-46: Tests helper now surfaces execution and client IP — LGTM.

  • Pulling x-appwrite-execution-id and x-appwrite-client-ip from headers and echoing them in the JSON response is aligned with the new behavior.
tests/e2e/Services/Functions/FunctionsCustomServerTest.php (1)

1337-1340: Server-side E2E parity — looks good.

  • Mirroring the client test here reduces the chance of environment-specific regressions. Nice.
src/Appwrite/Platform/Workers/Functions.php (1)

416-418: LGTM: single-source execution ID when creating a new execution

Generating a new $executionId only when the document is missing and immediately reflecting it into the header keeps the ID consistent between the header and the persisted Execution.

$headers['x-appwrite-user-id'] = '';
$headers['x-appwrite-country-code'] = '';
$headers['x-appwrite-continent-code'] = '';
$headers['x-appwrite-continent-eu'] = 'false';
$headers['x-appwrite-client-ip'] = $request->getIP();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Ensure header allowlist includes new headers.

  • You set x-appwrite-client-ip here. Confirm FUNCTION_ALLOWLIST_HEADERS_REQUEST contains both x-appwrite-execution-id and x-appwrite-client-ip; otherwise they’ll be filtered out of requestHeaders (even though the executor still gets $headers), and any tooling that relies on persisted headers may miss them.

Run this to verify:


🏁 Script executed:

#!/bin/bash
# Verify these headers are allowlisted (request side) and not treated as user-overrideable.
rg -nP '(?i)FUNCTION_ALLOWLIST_HEADERS_REQUEST|FUNCTION_ALLOWLIST_HEADERS_RESPONSE' -A3 -B3
rg -nP '(?i)x-appwrite-execution-id|x-appwrite-client-ip'

# Also confirm validator accepts/ignores them as expected.
rg -nP 'class\s+Headers\b|allow(ed)?Headers' --type=php -C3

Length of output: 7644


Add new Appwrite headers to the request allowlist

The new headers x-appwrite-execution-id and x-appwrite-client-ip are being set in app/controllers/general.php (and in several Functions runners) but are not present in the request‐side allowlist. As a result, they will be stripped out by the header filter and never make it into requestHeaders.

Please update your constants as follows:

• File: app/init/constants.php

- const FUNCTION_ALLOWLIST_HEADERS_REQUEST = ['content-type', 'agent', 'content-length', 'host'];
+ const FUNCTION_ALLOWLIST_HEADERS_REQUEST = [
+     'content-type',
+     'agent',
+     'content-length',
+     'host',
+     'x-appwrite-execution-id',
+     'x-appwrite-client-ip',
+ ];

Once added, the filter in app/controllers/general.php (around line 392) and in the Functions runners will correctly propagate both headers into requestHeaders so that any tooling or downstream logic relying on them continues to work.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$headers['x-appwrite-client-ip'] = $request->getIP();
++ b/app/init/constants.php
@@ -1,5 +1,8 @@
const FUNCTION_ALLOWLIST_HEADERS_REQUEST = [
'content-type',
'agent',
'content-length',
'host',
'x-appwrite-execution-id',
'x-appwrite-client-ip',
];
🤖 Prompt for AI Agents
In app/controllers/general.php around line 365 and the header filter near line
392, the new headers x-appwrite-execution-id and x-appwrite-client-ip are being
set but are not in the request-side allowlist, so they get stripped before
reaching requestHeaders; to fix this, add "x-appwrite-execution-id" and
"x-appwrite-client-ip" to the allowed headers constant array in
app/init/constants.php, then verify the header-filter logic in
app/controllers/general.php and the Functions runner files references that
constant so the filter will propagate these two headers into requestHeaders.

Comment on lines +267 to 274
$executionId = ID::unique();
$headers['x-appwrite-execution-id'] = $executionId ?? '';
$headers['x-appwrite-trigger'] = $trigger;
$headers['x-appwrite-event'] = $event ?? '';
$headers['x-appwrite-user-id'] = $user->getId() ?? '';
$headers['x-appwrite-user-jwt'] = $jwt ?? '';
$headers['x-appwrite-client-ip'] = '';

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Initialize $headers in fail(); fix potential undefined-variable usage and minor cleanups

fail() writes to $headers[...] without initializing $headers. In PHP 8+, assigning to an array offset on an undefined variable can emit notices and is brittle. Initialize $headers explicitly and avoid the redundant null coalescing on $executionId (it’s never null after ID::unique()).

Apply:

-        $executionId = ID::unique();
-        $headers['x-appwrite-execution-id'] = $executionId ?? '';
+        $executionId = ID::unique();
+        $headers = [];
+        $headers['x-appwrite-execution-id'] = $executionId;
         $headers['x-appwrite-trigger'] = $trigger;
         $headers['x-appwrite-event'] = $event ?? '';
         $headers['x-appwrite-user-id'] = $user->getId() ?? '';
         $headers['x-appwrite-user-jwt'] = $jwt ?? '';
-        $headers['x-appwrite-client-ip'] = '';
+        // Keep consistent behavior with worker: include header even if empty
+        $headers['x-appwrite-client-ip'] = $headers['x-appwrite-client-ip'] ?? '';
🤖 Prompt for AI Agents
In src/Appwrite/Platform/Workers/Functions.php around lines 267 to 274,
initialize $headers as an empty array before writing any offsets (e.g. $headers
= [];), remove the redundant null-coalescing on $executionId (since ID::unique()
never returns null) and keep/coalesce other values as needed (e.g.
$user->getId() ?? '' and $jwt ?? '') so assignments don't trigger
undefined-variable notices in PHP 8+ and the execution id isn't redundantly
coalesced.

$headers['x-appwrite-user-id'] = '';
$headers['x-appwrite-country-code'] = '';
$headers['x-appwrite-continent-code'] = '';
$headers['x-appwrite-continent-eu'] = 'false';
$headers['x-appwrite-client-ip'] = $request->getIP();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point by CodeRabbit here, let's add client IP header to whitelist of request headers, so it can be seen in Console by developer.

It's not privacy issue as tracking IP is allowed for security reasons, and we anyway already store IP of sessions, so our compliance already cover it.

$headers['x-appwrite-key'] = API_KEY_DYNAMIC . '_' . $apiKey;
$headers['x-appwrite-trigger'] = 'http';
$headers['x-appwrite-user-id'] = $user->getId() ?? '';
$headers['x-appwrite-user-jwt'] = $jwt ?? '';
$headers['x-appwrite-country-code'] = '';
$headers['x-appwrite-continent-code'] = '';
$headers['x-appwrite-continent-eu'] = 'false';
$headers['x-appwrite-client-ip'] = $request->getIP();

$ip = $headers['x-real-ip'] ?? '';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm this seems wrong now, I think we should use $request->getIP() here too.

Let's check where else we use this x-real-ip directly, and consider replacing it there as well

$headers['x-appwrite-trigger'] = $trigger;
$headers['x-appwrite-event'] = $event ?? '';
$headers['x-appwrite-user-id'] = $user->getId() ?? '';
$headers['x-appwrite-user-jwt'] = $jwt ?? '';
$headers['x-appwrite-client-ip'] = '';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree with CodeRabbit here - if headers already have client IP, we shouldn't replace it. Only set it to empty string if we dont have it already

@@ -405,18 +408,20 @@ private function execute(
$headers['x-appwrite-country-code'] = '';
$headers['x-appwrite-continent-code'] = '';
$headers['x-appwrite-continent-eu'] = 'false';
$headers['x-appwrite-client-ip'] = '';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here, let's only set to empty if its not already there

@@ -159,6 +159,11 @@ public function testCreateCustomExecution(): array
$this->assertNotEmpty($output['APPWRITE_FUNCTION_JWT']);
$this->assertEquals($this->getProject()['$id'], $output['APPWRITE_FUNCTION_PROJECT_ID']);

$executionId = $execution['body']['$id'] ?? '';
$this->assertNotEmpty($output['APPWRITE_FUNCTION_EXECUTION_ID']);
$this->assertEquals($executionId, $output['APPWRITE_FUNCTION_EXECUTION_ID']);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would do 1 more assertion, in async flow. async execution, or event trigger, or schedule, anywhere.

There we should assert execution ID exists, but client IP is empty

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

🚀 Enhancement: Expose execution ID in function execution
6 participants