Skip to content

Commit

Permalink
fix(dynamite): Fix pattern check for enums
Browse files Browse the repository at this point in the history
Signed-off-by: jld3103 <[email protected]>
  • Loading branch information
provokateurin committed Dec 18, 2023
1 parent 0c2c5fe commit befbd0b
Show file tree
Hide file tree
Showing 14 changed files with 228 additions and 141 deletions.
17 changes: 4 additions & 13 deletions packages/dynamite/dynamite/lib/src/builder/client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,6 @@ Iterable<Method> buildTags(
),
);

buildParameterPatternCheck(parameter).forEach(code.writeln);
code.writeln(buildParameterSerialization(result, parameter));
}
resolveMimeTypeEncode(operation, spec, state, operationName, operationParameters).forEach(code.writeln);
Expand Down Expand Up @@ -444,6 +443,10 @@ String buildParameterSerialization(
buffer.writeln('$serializedName ??= $defaultValueCode;');
}

if (parameter.schema != null) {
buildPatternCheck(parameter.schema!, serializedName, dartName).forEach(buffer.writeln);
}

if (parameter.$in == openapi.ParameterType.header) {
final assignment =
"_headers['${parameter.pctEncodedName}'] = ${result.encode(serializedName, onlyChildren: true)};";
Expand All @@ -463,18 +466,6 @@ String buildParameterSerialization(
return buffer.toString();
}

Iterable<String> buildParameterPatternCheck(
final openapi.Parameter parameter,
) sync* {
final schema = parameter.schema;
if (schema == null) {
return;
}

final value = toDartName(parameter.name);
yield* buildPatternCheck(schema, value);
}

Iterable<String> buildAuthCheck(
final MapEntry<String, openapi.PathItem> pathEntry,
final openapi.Operation operation,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ TypeResultObject resolveObject(
validators.add('b.$dartName?.validateAnyOf();');
}

validators.addAll(buildPatternCheck(propertySchema, 'b.$dartName'));
validators.addAll(buildPatternCheck(propertySchema, 'b.$dartName', dartName));
}

final $interface = buildInterface(
Expand Down
9 changes: 4 additions & 5 deletions packages/dynamite/dynamite/lib/src/helpers/pattern_check.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,17 @@ import 'package:dynamite/src/models/openapi/schema.dart';
Iterable<String> buildPatternCheck(
final openapi.Schema schema,
final String value,
final String name,
) sync* {
final name = "'$value'";

if (schema.type == SchemaType.string) {
if (schema.pattern != null) {
yield "dynamite_utils.checkPattern($value, RegExp(r'${schema.pattern!}'), $name);";
yield "dynamite_utils.checkPattern($value as String?, RegExp(r'${schema.pattern!}'), '$name');";
}
if (schema.minLength != null) {
yield 'dynamite_utils.checkMinLength($value, ${schema.minLength}, $name);';
yield "dynamite_utils.checkMinLength($value as String?, ${schema.minLength}, '$name');";
}
if (schema.maxLength != null) {
yield 'dynamite_utils.checkMaxLength($value, ${schema.maxLength}, $name);';
yield "dynamite_utils.checkMaxLength($value as String?, ${schema.maxLength}, '$name');";
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import 'dart:typed_data';

import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:built_value/json_object.dart';
import 'package:built_value/serializer.dart';
import 'package:built_value/standard_json_plugin.dart';
Expand All @@ -17,6 +18,8 @@ import 'package:meta/meta.dart';
import 'package:universal_io/io.dart';
import 'package:uri/uri.dart';

part 'parameters.openapi.g.dart';

class Client extends DynamiteClient {
Client(
super.baseURL, {
Expand Down Expand Up @@ -51,6 +54,7 @@ class Client extends DynamiteClient {
/// * [object]
/// * [oneOf]
/// * [anyOf]
/// * [enumPattern]
///
/// Status codes:
/// * 200
Expand All @@ -70,6 +74,7 @@ class Client extends DynamiteClient {
final JsonObject? object,
final GetOneOf? oneOf,
final GetAnyOf? anyOf,
final GetEnumPattern? enumPattern,
}) async {
final rawResponse = $getRaw(
contentString: contentString,
Expand All @@ -84,6 +89,7 @@ class Client extends DynamiteClient {
object: object,
oneOf: oneOf,
anyOf: anyOf,
enumPattern: enumPattern,
);

return rawResponse.future;
Expand All @@ -107,6 +113,7 @@ class Client extends DynamiteClient {
/// * [object]
/// * [oneOf]
/// * [anyOf]
/// * [enumPattern]
///
/// Status codes:
/// * 200
Expand All @@ -127,6 +134,7 @@ class Client extends DynamiteClient {
final JsonObject? object,
final GetOneOf? oneOf,
final GetAnyOf? anyOf,
final GetEnumPattern? enumPattern,
}) {
final parameters = <String, dynamic>{};
final headers = <String, String>{
Expand Down Expand Up @@ -180,9 +188,13 @@ class Client extends DynamiteClient {
final $anyOf = jsonSerializers.serialize(anyOf, specifiedType: const FullType(GetAnyOf));
parameters['anyOf'] = $anyOf;

final $enumPattern = jsonSerializers.serialize(enumPattern, specifiedType: const FullType(GetEnumPattern));
dynamite_utils.checkPattern($enumPattern as String?, RegExp('[a-z]'), 'enumPattern');
parameters['enum_pattern'] = $enumPattern;

final uri = Uri.parse(
UriTemplate(
'/{?content_string*,content_parameter*,array*,bool*,string*,string_binary*,int*,double*,num*,object*,oneOf*,anyOf*}',
'/{?content_string*,content_parameter*,array*,bool*,string*,string_binary*,int*,double*,num*,object*,oneOf*,anyOf*,enum_pattern*}',
).expand(parameters),
);
return DynamiteRawResponse<JsonObject, void>(
Expand Down Expand Up @@ -366,6 +378,21 @@ class Client extends DynamiteClient {
}
}

class GetEnumPattern extends EnumClass {
const GetEnumPattern._(super.name);

static const GetEnumPattern a = _$getEnumPatternA;

@BuiltValueEnumConst(wireName: '0')
static const GetEnumPattern $0 = _$getEnumPattern$0;

static BuiltSet<GetEnumPattern> get values => _$getEnumPatternValues;

static GetEnumPattern valueOf(final String name) => _$valueOfGetEnumPattern(name);

static Serializer<GetEnumPattern> get serializer => _$getEnumPatternSerializer;
}

typedef GetOneOf = ({bool? $bool, String? string});

typedef GetAnyOf = ({bool? $bool, String? string});
Expand Down Expand Up @@ -442,7 +469,8 @@ final Serializers serializers = (Serializers().toBuilder()
)
..add(ContentString.serializer)
..addBuilderFactory(const FullType(BuiltList, [FullType(String)]), ListBuilder<String>.new)
..add($BoolStringExtension.serializer))
..add($BoolStringExtension.serializer)
..add(GetEnumPattern.serializer))
.build();

@visibleForTesting
Expand Down

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

Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,18 @@
}
]
}
},
{
"name": "enum_pattern",
"in": "query",
"schema": {
"type": "string",
"pattern": "[a-z]",
"enum": [
"a",
"0"
]
}
}
],
"responses": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,12 @@ abstract class TestObject implements $TestObjectInterface, Built<TestObject, Tes

@BuiltValueHook(finalizeBuilder: true)
static void _validate(final TestObjectBuilder b) {
dynamite_utils.checkPattern(b.onlyNumbers, RegExp(r'^[0-9]*$'), 'b.onlyNumbers');
dynamite_utils.checkMinLength(b.minLength, 3, 'b.minLength');
dynamite_utils.checkMaxLength(b.maxLength, 20, 'b.maxLength');
dynamite_utils.checkPattern(b.multipleChecks, RegExp(r'^[0-9]*$'), 'b.multipleChecks');
dynamite_utils.checkMinLength(b.multipleChecks, 3, 'b.multipleChecks');
dynamite_utils.checkMaxLength(b.multipleChecks, 20, 'b.multipleChecks');
dynamite_utils.checkPattern(b.onlyNumbers, RegExp(r'^[0-9]*$'), 'onlyNumbers');
dynamite_utils.checkMinLength(b.minLength, 3, 'minLength');
dynamite_utils.checkMaxLength(b.maxLength, 20, 'maxLength');
dynamite_utils.checkPattern(b.multipleChecks, RegExp(r'^[0-9]*$'), 'multipleChecks');
dynamite_utils.checkMinLength(b.multipleChecks, 3, 'multipleChecks');
dynamite_utils.checkMaxLength(b.multipleChecks, 20, 'multipleChecks');
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,19 @@ void main() {

group('Pattern check', () {
test('onlyNumbers', () {
expect(() => object.rebuild((final b) => b..onlyNumbers = null), throwsA(isA<FormatException>()));
object.rebuild((final b) => b..onlyNumbers = null);
expect(() => object.rebuild((final b) => b..onlyNumbers = 'Text'), throwsA(isA<FormatException>()));
});

test('minLength', () {
expect(() => object.rebuild((final b) => b..minLength = null), throwsA(isA<FormatException>()));
object.rebuild((final b) => b..minLength = null);
expect(() => object.rebuild((final b) => b..minLength = ''), throwsA(isA<FormatException>()));
expect(() => object.rebuild((final b) => b..minLength = 'Te'), throwsA(isA<FormatException>()));
expect(() => object.rebuild((final b) => b..minLength = '12'), throwsA(isA<FormatException>()));
});

test('maxLength', () {
expect(() => object.rebuild((final b) => b..maxLength = null), throwsA(isA<FormatException>()));
object.rebuild((final b) => b..maxLength = null);
expect(
() => object.rebuild((final b) => b..maxLength = 'Super long text should throw'),
throwsA(isA<FormatException>()),
Expand All @@ -37,7 +37,7 @@ void main() {
});

test('multipleChecks', () {
expect(() => object.rebuild((final b) => b..multipleChecks = null), throwsA(isA<FormatException>()));
object.rebuild((final b) => b..multipleChecks = null);
expect(() => object.rebuild((final b) => b..multipleChecks = 'Text'), throwsA(isA<FormatException>()));
expect(() => object.rebuild((final b) => b..minLength = ''), throwsA(isA<FormatException>()));
expect(() => object.rebuild((final b) => b..minLength = '12'), throwsA(isA<FormatException>()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
///
/// Throws an `Exception` containing the [parameterName] if the `pattern` does not match.
void checkPattern(final String? input, final RegExp pattern, final String parameterName) {
if (input == null || !pattern.hasMatch(input)) {
if (input != null && !pattern.hasMatch(input)) {
throw FormatException('Invalid value "$input" for parameter "$parameterName" with pattern "${pattern.pattern}"');
}
}
Expand All @@ -11,7 +11,7 @@ void checkPattern(final String? input, final RegExp pattern, final String parame
///
/// Throws an `Exception` containing the [parameterName] if the `input` is to short.
void checkMinLength(final String? input, final int minLength, final String parameterName) {
if (input == null || input.length < minLength) {
if (input != null && input.length < minLength) {
throw FormatException('Parameter "$input" has to be at least $minLength characters long');
}
}
Expand All @@ -20,7 +20,7 @@ void checkMinLength(final String? input, final int minLength, final String param
///
/// Throws an `Exception` containing the [parameterName] if the `input` is to long.
void checkMaxLength(final String? input, final int maxLength, final String parameterName) {
if (input == null || input.length > maxLength) {
if (input != null && input.length > maxLength) {
throw FormatException('Parameter "$input" has to be at most $maxLength characters long');
}
}
2 changes: 1 addition & 1 deletion packages/nextcloud/lib/src/api/files.openapi.dart
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,8 @@ class ApiClient {
final $y = jsonSerializers.serialize(y, specifiedType: const FullType(int));
parameters['y'] = $y;

dynamite_utils.checkPattern(file, RegExp(r'^.+$'), 'file');
final $file = jsonSerializers.serialize(file, specifiedType: const FullType(String));
dynamite_utils.checkPattern($file as String?, RegExp(r'^.+$'), 'file');
parameters['file'] = $file;

final uri = Uri.parse(UriTemplate('/index.php/apps/files/api/v1/thumbnail/{x}/{y}/{file}').expand(parameters));
Expand Down
6 changes: 3 additions & 3 deletions packages/nextcloud/lib/src/api/files_reminders.openapi.dart
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,8 @@ class ApiClient {
}

// coverage:ignore-end
dynamite_utils.checkPattern(version, RegExp(r'^1$'), 'version');
final $version = jsonSerializers.serialize(version, specifiedType: const FullType(String));
dynamite_utils.checkPattern($version as String?, RegExp(r'^1$'), 'version');
parameters['version'] = $version;

final $fileId = jsonSerializers.serialize(fileId, specifiedType: const FullType(int));
Expand Down Expand Up @@ -240,8 +240,8 @@ class ApiClient {
final $dueDate = jsonSerializers.serialize(dueDate, specifiedType: const FullType(String));
parameters['dueDate'] = $dueDate;

dynamite_utils.checkPattern(version, RegExp(r'^1$'), 'version');
final $version = jsonSerializers.serialize(version, specifiedType: const FullType(String));
dynamite_utils.checkPattern($version as String?, RegExp(r'^1$'), 'version');
parameters['version'] = $version;

final $fileId = jsonSerializers.serialize(fileId, specifiedType: const FullType(int));
Expand Down Expand Up @@ -347,8 +347,8 @@ class ApiClient {
}

// coverage:ignore-end
dynamite_utils.checkPattern(version, RegExp(r'^1$'), 'version');
final $version = jsonSerializers.serialize(version, specifiedType: const FullType(String));
dynamite_utils.checkPattern($version as String?, RegExp(r'^1$'), 'version');
parameters['version'] = $version;

final $fileId = jsonSerializers.serialize(fileId, specifiedType: const FullType(int));
Expand Down
Loading

0 comments on commit befbd0b

Please sign in to comment.