Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 28 additions & 6 deletions app/src/internal/FirebaseInterops.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ internal static class FirebaseInterops
private static Type _appCheckType;
private static MethodInfo _appCheckGetInstanceMethod;
private static MethodInfo _appCheckGetTokenMethod;
private static MethodInfo _appCheckGetLimitedUseTokenMethod;
private static PropertyInfo _appCheckTokenResultProperty;
private static PropertyInfo _appCheckTokenTokenProperty;
// Used to determine if the App Check reflection initialized successfully, and should work.
Expand Down Expand Up @@ -153,6 +154,7 @@ private static void InitializeAppCheckReflection()
{
const string firebaseAppCheckTypeName = "Firebase.AppCheck.FirebaseAppCheck, Firebase.AppCheck";
const string getAppCheckTokenMethodName = "GetAppCheckTokenAsync";
const string getLimitedUseAppCheckTokenMethodName = "GetLimitedUseAppCheckTokenAsync";

try
{
Expand Down Expand Up @@ -185,6 +187,16 @@ private static void InitializeAppCheckReflection()
return;
}

// Get the instance method GetLimitedUseAppCheckTokenAsync()
_appCheckGetLimitedUseTokenMethod = _appCheckType.GetMethod(
getLimitedUseAppCheckTokenMethodName, BindingFlags.Instance | BindingFlags.Public, null,
Type.EmptyTypes, null);
if (_appCheckGetLimitedUseTokenMethod == null)
{
LogError($"Could not find {getLimitedUseAppCheckTokenMethodName} method via reflection.");
return;
Comment thread
AustinBenoit marked this conversation as resolved.
}

// Should be Task<AppCheckToken>
Type appCheckTokenTaskType = _appCheckGetTokenMethod.ReturnType;

Expand Down Expand Up @@ -215,7 +227,7 @@ private static void InitializeAppCheckReflection()
}

// Gets the AppCheck Token, assuming there is one. Otherwise, returns null.
internal static async Task<string> GetAppCheckTokenAsync(FirebaseApp firebaseApp)
internal static async Task<string> GetAppCheckTokenAsync(FirebaseApp firebaseApp, bool limitedUse = false)
{
// If AppCheck reflection failed for any reason, nothing to do.
if (!_appCheckReflectionInitialized)
Expand All @@ -233,8 +245,17 @@ internal static async Task<string> GetAppCheckTokenAsync(FirebaseApp firebaseApp
return null;
}

// Invoke GetAppCheckTokenAsync(false) - returns a Task<AppCheckToken>
object taskObject = _appCheckGetTokenMethod.Invoke(appCheckInstance, new object[] { false });
object taskObject;
if (limitedUse)
{
taskObject = _appCheckGetLimitedUseTokenMethod.Invoke(appCheckInstance, null);
}
else
{
// Invoke GetAppCheckTokenAsync(false) - returns a Task<AppCheckToken>
taskObject = _appCheckGetTokenMethod.Invoke(appCheckInstance, new object[] { false });
}

if (taskObject is not Task appCheckTokenTask)
{
LogError($"Invoking GetToken did not return a Task.");
Expand All @@ -260,7 +281,8 @@ internal static async Task<string> GetAppCheckTokenAsync(FirebaseApp firebaseApp
}

// Get the Token property from the AppCheckToken struct
return _appCheckTokenTokenProperty.GetValue(tokenResult) as string;
string finalToken = _appCheckTokenTokenProperty.GetValue(tokenResult) as string;
return finalToken;
}
catch (Exception e)
{
Expand Down Expand Up @@ -404,9 +426,9 @@ internal static async Task<string> GetAuthTokenAsync(FirebaseApp firebaseApp)
}

// Adds the other Firebase tokens to the HttpRequest, as available.
internal static async Task AddFirebaseTokensAsync(HttpRequestMessage request, FirebaseApp firebaseApp, string authTokenPrefix = "Firebase")
internal static async Task AddFirebaseTokensAsync(HttpRequestMessage request, FirebaseApp firebaseApp, string authTokenPrefix = "Firebase", bool limitedUseAppCheckTokens = false)
{
string appCheckToken = await GetAppCheckTokenAsync(firebaseApp);
string appCheckToken = await GetAppCheckTokenAsync(firebaseApp, limitedUseAppCheckTokens);
if (!string.IsNullOrEmpty(appCheckToken))
{
request.Headers.Add(appCheckHeader, appCheckToken);
Expand Down
4 changes: 2 additions & 2 deletions app/src/internal/HttpHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ namespace Firebase.Internal
// Helper functions to help handling the Http calls.
internal static class HttpHelpers
{
internal static async Task SetRequestHeaders(HttpRequestMessage request, FirebaseApp firebaseApp, string authPrefix = "Firebase")
internal static async Task SetRequestHeaders(HttpRequestMessage request, FirebaseApp firebaseApp, string authPrefix = "Firebase", bool limitedUseAppCheckTokens = false)
{
request.Headers.Add("x-goog-api-key", firebaseApp.Options.ApiKey);
string version = FirebaseInterops.GetVersionInfoSdkVersion();
Expand All @@ -35,7 +35,7 @@ internal static async Task SetRequestHeaders(HttpRequestMessage request, Firebas
request.Headers.Add("X-Firebase-AppVersion", UnityEngine.Application.version);
}
// Add additional Firebase tokens to the header.
await FirebaseInterops.AddFirebaseTokensAsync(request, firebaseApp, authPrefix);
await FirebaseInterops.AddFirebaseTokensAsync(request, firebaseApp, authPrefix, limitedUseAppCheckTokens);
}

// Helper function to throw an exception if the Http Response indicates failure.
Expand Down
1 change: 1 addition & 0 deletions docs/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ Release Notes
- Storage: Added `ListAsync` API to list items and prefixes under a reference.
- Functions: Fixed tgz export, added missing asmdef for functions. Fixes issue where Functions were not being exported correctly in the tgz build.
- Firebase AI: Fix tgz export, added missing asmdef for Firebase AI. Fixes issue where Firebase AI was not being exported correctly in the tgz build.
- Functions: Added support for passing and enforcing Limited Use App Check tokens.

### 13.10.0
- Changes
Expand Down
12 changes: 6 additions & 6 deletions functions/src/FirebaseFunctions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -228,22 +228,22 @@ private string GetUrl(in string name) {
/// <summary>
/// Creates a <see cref="HttpsCallableReference" /> given a name.
/// </summary>
public HttpsCallableReference GetHttpsCallable(string name) {
return new HttpsCallableReference(this, GetUrl(name));
public HttpsCallableReference GetHttpsCallable(string name, HttpsCallableOptions options = null) {
return new HttpsCallableReference(this, GetUrl(name), options);
}

/// <summary>
/// Creates a <see cref="HttpsCallableReference" /> given a URL.
/// </summary>
public HttpsCallableReference GetHttpsCallableFromURL(string url) {
return new HttpsCallableReference(this, url);
public HttpsCallableReference GetHttpsCallableFromURL(string url, HttpsCallableOptions options = null) {
return new HttpsCallableReference(this, url, options);
}

/// <summary>
/// Creates a <see cref="HttpsCallableReference" /> given a URL.
/// </summary>
public HttpsCallableReference GetHttpsCallableFromURL(Uri url) {
return GetHttpsCallableFromURL(url.ToString());
public HttpsCallableReference GetHttpsCallableFromURL(Uri url, HttpsCallableOptions options = null) {
return GetHttpsCallableFromURL(url.ToString(), options);
}

/// <summary>
Expand Down
30 changes: 30 additions & 0 deletions functions/src/HttpsCallableOptions.cs
Comment thread
AustinBenoit marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Firebase.Functions
{
/// <summary>
/// Options to configure a Callable Function reference.
/// </summary>
public sealed class HttpsCallableOptions
{
/// <summary>
/// If set to true, uses limited use App Check token for callable function requests from this
/// instance of Functions. By default, this is false.
/// </summary>
public bool LimitedUseAppCheckTokens { get; set; }
}
}
7 changes: 7 additions & 0 deletions functions/src/HttpsCallableOptions.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions functions/src/HttpsCallableReference.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,15 @@ public sealed class HttpsCallableReference
// Functions object this reference was created from.
private readonly FirebaseFunctions _firebaseFunctions;
private readonly string _url;
private readonly HttpsCallableOptions _options;
/// <summary>
/// Construct a wrapper around the HttpsCallableReferenceInternal object.
/// </summary>
internal HttpsCallableReference(FirebaseFunctions functions, string url)
internal HttpsCallableReference(FirebaseFunctions functions, string url, HttpsCallableOptions options = null)
{
_firebaseFunctions = functions;
_url = url;
_options = options;
}

/// <summary>
Expand Down Expand Up @@ -90,7 +92,8 @@ private async Task<HttpsCallableResult> InternalCallAsync(object data)
HttpRequestMessage request = new(HttpMethod.Post, _url);
// Functions uses Bearer tokens for authentication.
// This is different from the default Firebase token prefix used by other Firebase services.
await HttpHelpers.SetRequestHeaders(request, _firebaseFunctions.App, "Bearer");
bool limitedUseAppCheckTokens = _options != null && _options.LimitedUseAppCheckTokens;
await HttpHelpers.SetRequestHeaders(request, _firebaseFunctions.App, "Bearer", limitedUseAppCheckTokens);
request.Content = MakeFunctionsRequest(data);

#if FIREBASE_LOG_REST_CALLS
Expand Down
21 changes: 15 additions & 6 deletions functions/testapp/Assets/Firebase/Sample/Functions/TestCase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,12 @@ namespace Firebase.Sample.Functions {
using System.Threading.Tasks;

public class TestCase {
// The name of the HTTPS callable function to call.
// The display name of the test.
public string Name { get; private set; }

// The name of the HTTPS callable function to call.
public string FunctionName { get; private set; }

// The parameters to pass to the function.
public object Input { get; private set; }

Expand All @@ -32,18 +35,24 @@ public class TestCase {
// The error code expected to be returned from the function.
public FunctionsErrorCode ExpectedError { get; private set; }

public TestCase(string name, object input, object expectedResult,
FunctionsErrorCode expectedError = FunctionsErrorCode.None) {
// The options to pass to the function.
public HttpsCallableOptions Options { get; private set; }

public TestCase(string name, string functionName, object input, object expectedResult,
FunctionsErrorCode expectedError = FunctionsErrorCode.None,
HttpsCallableOptions options = null) {
Name = name;
FunctionName = functionName;
Input = input;
ExpectedData = expectedResult;
ExpectedError = expectedError;
Options = options;
}

// Returns the CallableReference to be used by the test. Overridable to allow
// different ways to generate the CallableReference.
public virtual HttpsCallableReference GetReference(FirebaseFunctions functions) {
return functions.GetHttpsCallable(Name);
return functions.GetHttpsCallable(FunctionName, Options);
}

// Runs the given test and returns whether it passed.
Expand Down Expand Up @@ -96,13 +105,13 @@ public class TestCaseWithURL : TestCase {

public TestCaseWithURL(string name, System.Uri url, object input, object expectedResult,
FunctionsErrorCode expectedError = FunctionsErrorCode.None)
: base(name, input, expectedResult, expectedError) {
: base(name, url.ToString(), input, expectedResult, expectedError) {
URL = url;
}

// Generate the CallableReference using the URL
public override HttpsCallableReference GetReference(FirebaseFunctions functions) {
return functions.GetHttpsCallableFromURL(URL);
return functions.GetHttpsCallableFromURL(URL, Options);
}
}
}
Comment thread
AustinBenoit marked this conversation as resolved.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ namespace Firebase.Sample.Functions {
using Firebase;
using Firebase.Extensions;
using Firebase.Functions;

using System;
using System.Collections;
using System.Collections.Generic;
Expand All @@ -35,10 +36,12 @@ public class UIHandler : MonoBehaviour {
private DependencyStatus dependencyStatus = DependencyStatus.UnavailableOther;
protected FirebaseFunctions functions;


// When the app starts, check to make sure that we have
// the required dependencies to use Firebase, and if not,
// add them if possible.
protected virtual void Start() {

FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => {
dependencyStatus = task.Result;
if (dependencyStatus == DependencyStatus.Available) {
Expand All @@ -50,6 +53,8 @@ protected virtual void Start() {
});
}



protected virtual void InitializeFirebase() {
functions = FirebaseFunctions.DefaultInstance;
UIEnabled = true;
Expand Down Expand Up @@ -93,6 +98,7 @@ protected void GUIDisplayTests() {
if (GUILayout.Button("addNumbers")) {
StartCoroutine(AddNumbers(5, 7));
}

GUILayout.EndVertical();
}

Expand All @@ -117,6 +123,8 @@ protected IEnumerator AddNumbers(int firstNumber, int secondNumber) {
yield return new WaitUntil(() => task.IsCompleted);
}



// Render the buttons and other controls.
void GUIDisplayControls() {
if (UIEnabled) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
namespace Firebase.Sample.Functions {
using Firebase;
using Firebase.AppCheck;
using Firebase.Extensions;
using Firebase.Functions;
using System;
Expand All @@ -10,6 +12,7 @@ namespace Firebase.Sample.Functions {
public class UIHandlerAutomated : UIHandler {
private Firebase.Sample.AutomatedTestRunner testRunner;
private Firebase.Auth.FirebaseAuth firebaseAuth;
private string appCheckDebugTokenForAutomated = "REPLACE_WITH_APP_CHECK_TOKEN";

// Returns the set of all integration tests.
public static IEnumerable<TestCase> AllTests() {
Expand All @@ -35,24 +38,37 @@ public static IEnumerable<TestCase> AllTests() {
expectedArray.Add(3L);
expected["array"] = expectedArray;

yield return new TestCase("dataTest", data, expected);
yield return new TestCase("dataTest", "dataTest", data, expected);
}

{
var data = new Dictionary<string, object>();
data["firstNumber"] = 5;
data["secondNumber"] = 7;
var expected = new Dictionary<string, object>();
expected["firstNumber"] = 5L;
expected["secondNumber"] = 7L;
expected["operator"] = "+";
expected["operationResult"] = 12L;
yield return new TestCase("addNumbersWithLimitedUse", "addNumbers", data, expected, FunctionsErrorCode.None, new HttpsCallableOptions { LimitedUseAppCheckTokens = true });
}

var empty = new Dictionary<string, object>();
yield return new TestCase("scalarTest", 17, 76L);
yield return new TestCase("tokenTest", empty, empty);
yield return new TestCase("scalarTest", "scalarTest", 17, 76L);
yield return new TestCase("scalarTestwithLimitedUse", "scalarTest", 17, 76L, FunctionsErrorCode.None, new HttpsCallableOptions { LimitedUseAppCheckTokens = true });
yield return new TestCase("tokenTest", "tokenTest", empty, empty);
// Only run this on iOS and Android.
// yield return new TestCase("instanceIdTest", empty, empty);
yield return new TestCase("nullTest", null, null);
// yield return new TestCase("instanceIdTest", "instanceIdTest", empty, empty);
yield return new TestCase("nullTest", "nullTest", null, null);

// Test various error cases.
yield return new TestCase("missingResultTest", null, null,
yield return new TestCase("missingResultTest", "missingResultTest", null, null,
FunctionsErrorCode.Internal);
yield return new TestCase("unhandledErrorTest", null, null,
yield return new TestCase("unhandledErrorTest", "unhandledErrorTest", null, null,
FunctionsErrorCode.Internal);
yield return new TestCase("unknownErrorTest", null, null,
yield return new TestCase("unknownErrorTest", "unknownErrorTest", null, null,
FunctionsErrorCode.Internal);
yield return new TestCase("explicitErrorTest", null, null,
yield return new TestCase("explicitErrorTest", "explicitErrorTest", null, null,
FunctionsErrorCode.OutOfRange);

// Test calling via Url
Expand All @@ -63,6 +79,7 @@ public static IEnumerable<TestCase> AllTests() {
}

protected override void Start() {
InitializeAppCheck();
// Set the list of tests to run, note this is done at Start since they are
// non-static.
var testCases = AllTests().ToArray();
Expand All @@ -76,9 +93,16 @@ protected override void Start() {
);

UIEnabled = false;

base.Start();
}

protected void InitializeAppCheck() {
DebugLog("Initializing App Check directly in automated handler");
DebugAppCheckProviderFactory.Instance.SetDebugToken(appCheckDebugTokenForAutomated);
FirebaseAppCheck.SetAppCheckProviderFactory(DebugAppCheckProviderFactory.Instance);
}

protected override void InitializeFirebase() {
// One of the automated tests requires Auth, so we want to sign in before running it.
firebaseAuth = Firebase.Auth.FirebaseAuth.DefaultInstance;
Expand Down
Loading
Loading