1 /* 2 * Copyright (C) 2023 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.adservices.service.common; 18 19 import androidx.annotation.NonNull; 20 21 import com.android.adservices.LoggerFactory; 22 import com.android.adservices.service.Flags; 23 24 import com.google.common.annotations.VisibleForTesting; 25 26 import java.nio.charset.StandardCharsets; 27 import java.util.Locale; 28 29 /** Validate Ad Render Id. */ 30 public interface AdRenderIdValidator extends Validator<String> { 31 @VisibleForTesting 32 String AD_RENDER_ID_TOO_LONG = "Ad Render Id exceeds max length %d, length is %d."; 33 34 AdRenderIdValidator AD_RENDER_ID_VALIDATOR_NO_OP = (object, violations) -> {}; 35 36 /** 37 * @return an instance of {@code AdRenderIdValidator} reading the configuration from {@code 38 * flags}. 39 */ createInstance(Flags flags)40 static AdRenderIdValidator createInstance(Flags flags) { 41 LoggerFactory.Logger logger = LoggerFactory.getFledgeLogger(); 42 boolean adRenderIdEnabled = flags.getFledgeAuctionServerAdRenderIdEnabled(); 43 if (!adRenderIdEnabled) { 44 logger.v("Ad render ID disabled"); 45 return AD_RENDER_ID_VALIDATOR_NO_OP; 46 } else { 47 final long maxLength = flags.getFledgeAuctionServerAdRenderIdMaxLength(); 48 logger.v("Ad render ID enabled with max length %d", maxLength); 49 return createEnabledInstance(maxLength); 50 } 51 } 52 53 /** 54 * @return an instance of {@code AdRenderIdValidator} that will enforce the given {@code 55 * maxLength} 56 */ 57 @NonNull createEnabledInstance(long maxLength)58 static AdRenderIdValidator createEnabledInstance(long maxLength) { 59 return (object, violations) -> { 60 if (object != null && object.getBytes(StandardCharsets.UTF_8).length > maxLength) { 61 violations.add( 62 String.format( 63 Locale.ENGLISH, 64 AD_RENDER_ID_TOO_LONG, 65 maxLength, 66 object.getBytes(StandardCharsets.UTF_8).length)); 67 } 68 }; 69 } 70 } 71