code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def set_flag_sql(flag, value, colmn = nil, custom_table_name = table_name) colmn = determine_flag_colmn_for(flag) if colmn.nil? sql_set_for_flag(flag, colmn, value, custom_table_name) end
Returns SQL statement to enable/disable flag. Automatically determines the correct column.
set_flag_sql
ruby
pboling/flag_shih_tzu
lib/flag_shih_tzu.rb
https://github.com/pboling/flag_shih_tzu/blob/master/lib/flag_shih_tzu.rb
MIT
def sql_in_for_flag(flag, colmn) val = flag_mapping[colmn][flag] flag_value_range_for_column(colmn).select { |bits| bits & val == val } end
returns an array of integers suitable for a SQL IN statement.
sql_in_for_flag
ruby
pboling/flag_shih_tzu
lib/flag_shih_tzu.rb
https://github.com/pboling/flag_shih_tzu/blob/master/lib/flag_shih_tzu.rb
MIT
def named_scope_method # Can't use respond_to because both AR 2 and 3 # respond to both +scope+ and +named_scope+. ActiveRecord::VERSION::MAJOR == 2 ? :named_scope : :scope end
Returns the correct method to create a named scope. Use to prevent deprecation notices on Rails 3 when using +named_scope+ instead of +scope+.
named_scope_method
ruby
pboling/flag_shih_tzu
lib/flag_shih_tzu.rb
https://github.com/pboling/flag_shih_tzu/blob/master/lib/flag_shih_tzu.rb
MIT
def enable_flag(flag, colmn = nil) colmn = determine_flag_colmn_for(flag) if colmn.nil? self.class.check_flag(flag, colmn) set_flags(flags(colmn) | self.class.flag_mapping[colmn][flag], colmn) end
Performs the bitwise operation so the flag will return +true+.
enable_flag
ruby
pboling/flag_shih_tzu
lib/flag_shih_tzu.rb
https://github.com/pboling/flag_shih_tzu/blob/master/lib/flag_shih_tzu.rb
MIT
def disable_flag(flag, colmn = nil) colmn = determine_flag_colmn_for(flag) if colmn.nil? self.class.check_flag(flag, colmn) set_flags(flags(colmn) & ~self.class.flag_mapping[colmn][flag], colmn) end
Performs the bitwise operation so the flag will return +false+.
disable_flag
ruby
pboling/flag_shih_tzu
lib/flag_shih_tzu.rb
https://github.com/pboling/flag_shih_tzu/blob/master/lib/flag_shih_tzu.rb
MIT
def update_flag!(flag, value, update_instance = false) truthy = FlagShihTzu::TRUE_VALUES.include?(value) sql = self.class.set_flag_sql(flag.to_sym, truthy) if update_instance if truthy enable_flag(flag) else disable_flag(flag) end end if (ActiveRecord::VERSION::MAJOR <= 3) self.class. update_all(sql, self.class.primary_key => id) == 1 else self.class. where("#{self.class.primary_key} = ?", id). update_all(sql) == 1 end end
returns true if successful third parameter allows you to specify that `self` should also have its in-memory flag attribute updated.
update_flag!
ruby
pboling/flag_shih_tzu
lib/flag_shih_tzu.rb
https://github.com/pboling/flag_shih_tzu/blob/master/lib/flag_shih_tzu.rb
MIT
def chained_flags_with_signature(colmn = DEFAULT_COLUMN_NAME, *args) flags_to_collect = args.empty? ? all_flags(colmn) : args truthy_and_chosen = selected_flags(colmn). select { |flag| flags_to_collect.include?(flag) } truthy_and_chosen.concat( collect_flags(*flags_to_collect) do |memo, flag| memo << "not_#{flag}".to_sym unless truthy_and_chosen.include?(flag) end ) end
Use with chained_flags_with to find records with specific flags set to the same values as on this record. For a record that has sent_warm_up_email = true and the other flags false: user.chained_flags_with_signature => [:sent_warm_up_email, :not_follow_up_called, :not_sent_final_email, :not_scheduled_appointment] User.chained_flags_with("flags", *user.chained_flags_with_signature) => the set of Users that have the same flags set as user.
chained_flags_with_signature
ruby
pboling/flag_shih_tzu
lib/flag_shih_tzu.rb
https://github.com/pboling/flag_shih_tzu/blob/master/lib/flag_shih_tzu.rb
MIT
def as_flag_collection(colmn = DEFAULT_COLUMN_NAME, *args) flags_to_collect = args.empty? ? all_flags(colmn) : args collect_flags(*flags_to_collect) do |memo, flag| memo << [flag, flag_enabled?(flag, colmn)] end end
Use with a checkbox form builder, like rails' or simple_form's :selected_flags, used in the example below, is a method defined by flag_shih_tzu for bulk setting flags like this: form_for @user do |f| f.collection_check_boxes(:selected_flags, f.object.as_flag_collection("flags", :sent_warm_up_email, :not_follow_up_called), :first, :last) end
as_flag_collection
ruby
pboling/flag_shih_tzu
lib/flag_shih_tzu.rb
https://github.com/pboling/flag_shih_tzu/blob/master/lib/flag_shih_tzu.rb
MIT
def validates_presence_of_flags(*attr_names) validates_with PresenceOfFlagsValidator, _merge_attributes(attr_names) end
Validates that the specified attributes are flags and are not blank. Happens by default on save. Example: class Spaceship < ActiveRecord::Base include FlagShihTzu has_flags({ 1 => :warpdrive, 2 => :hyperspace }, :column => 'engines') validates_presence_of_flags :engines end The engines attribute must be a flag in the object and it cannot be blank. Configuration options: * <tt>:message</tt> - A custom error message (default is: "can't be blank"). * <tt>:on</tt> - Specifies when this validation is active. Runs in all validation contexts by default (+nil+), other options are <tt>:create</tt> and <tt>:update</tt>. * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The method, proc or string should return or evaluate to a true or false value. * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |spaceship| spaceship.warp_step <= 2 }</tt>). The method, proc or string should return or evaluate to a true or false value. * <tt>:strict</tt> - Specifies whether validation should be strict. See <tt>ActiveModel::Validation#validates!</tt> for more information.
validates_presence_of_flags
ruby
pboling/flag_shih_tzu
lib/flag_shih_tzu/validators.rb
https://github.com/pboling/flag_shih_tzu/blob/master/lib/flag_shih_tzu/validators.rb
MIT
def fulfill(key, value) finish_resolve(key) do |promise| promise.fulfill(value) end end
Fulfill the key with provided value, for use in #perform
fulfill
ruby
Shopify/graphql-batch
lib/graphql/batch/loader.rb
https://github.com/Shopify/graphql-batch/blob/master/lib/graphql/batch/loader.rb
MIT
def fulfilled?(key) promise = promise_for(key) # When a promise is fulfilled through this class, it will either: # become fulfilled, if fulfilled with a literal value # become pending with a new source if fulfilled with a promise # Either of these is acceptable, promise.rb will automatically re-wait # on the new source promise as needed. return true if promise.fulfilled? promise.pending? && promise.source != self end
Returns true when the key has already been fulfilled, otherwise returns false
fulfilled?
ruby
Shopify/graphql-batch
lib/graphql/batch/loader.rb
https://github.com/Shopify/graphql-batch/blob/master/lib/graphql/batch/loader.rb
MIT
def perform(keys) raise NotImplementedError end
Must override to load the keys and call #fulfill for each key
perform
ruby
Shopify/graphql-batch
lib/graphql/batch/loader.rb
https://github.com/Shopify/graphql-batch/blob/master/lib/graphql/batch/loader.rb
MIT
def encode(payload, key, algorithm = 'HS256', header_fields = {}) Encode.new(payload: payload, key: key, algorithm: algorithm, headers: header_fields).segments end
Encodes a payload into a JWT. @param payload [Hash] the payload to encode. @param key [String] the key used to sign the JWT. @param algorithm [String] the algorithm used to sign the JWT. @param header_fields [Hash] additional headers to include in the JWT. @return [String] the encoded JWT.
encode
ruby
jwt/ruby-jwt
lib/jwt.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt.rb
MIT
def decode(jwt, key = nil, verify = true, options = {}, &keyfinder) # rubocop:disable Style/OptionalBooleanParameter Decode.new(jwt, key, verify, configuration.decode.to_h.merge(options), &keyfinder).decode_segments end
Decodes a JWT to extract the payload and header @param jwt [String] the JWT to decode. @param key [String] the key used to verify the JWT. @param verify [Boolean] whether to verify the JWT signature. @param options [Hash] additional options for decoding. @return [Array<Hash>] the decoded payload and headers.
decode
ruby
jwt/ruby-jwt
lib/jwt.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt.rb
MIT
def url_encode(str) ::Base64.urlsafe_encode64(str, padding: false) end
Encode a string with URL-safe Base64 complying with RFC 4648 (not padded). @api private
url_encode
ruby
jwt/ruby-jwt
lib/jwt/base64.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/base64.rb
MIT
def url_decode(str) ::Base64.urlsafe_decode64(str) rescue ArgumentError => e raise unless e.message == 'invalid base64' raise Base64DecodeError, 'Invalid base64 encoding' end
Decode a string with URL-safe Base64 complying with RFC 4648. @api private
url_decode
ruby
jwt/ruby-jwt
lib/jwt/base64.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/base64.rb
MIT
def verify_payload!(payload, *options) Verifier.verify!(VerificationContext.new(payload: payload), *options) end
Checks if the claims in the JWT payload are valid. @example ::JWT::Claims.verify_payload!({"exp" => Time.now.to_i + 10}, :exp) ::JWT::Claims.verify_payload!({"exp" => Time.now.to_i - 10}, exp: { leeway: 11}) @param payload [Hash] the JWT payload. @param options [Array] the options for verifying the claims. @return [void] @raise [JWT::DecodeError] if any claim is invalid.
verify_payload!
ruby
jwt/ruby-jwt
lib/jwt/claims.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/claims.rb
MIT
def valid_payload?(payload, *options) payload_errors(payload, *options).empty? end
Checks if the claims in the JWT payload are valid. @param payload [Hash] the JWT payload. @param options [Array] the options for verifying the claims. @return [Boolean] true if the claims are valid, false otherwise
valid_payload?
ruby
jwt/ruby-jwt
lib/jwt/claims.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/claims.rb
MIT
def payload_errors(payload, *options) Verifier.errors(VerificationContext.new(payload: payload), *options) end
Returns the errors in the claims of the JWT token. @param options [Array] the options for verifying the claims. @return [Array<JWT::Claims::Error>] the errors in the claims of the JWT
payload_errors
ruby
jwt/ruby-jwt
lib/jwt/claims.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/claims.rb
MIT
def configuration @configuration ||= ::JWT::Configuration::Container.new end
Returns the JWT configuration container. @return [JWT::Configuration::Container] the configuration container.
configuration
ruby
jwt/ruby-jwt
lib/jwt/configuration.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/configuration.rb
MIT
def initialize(jwt, key, verify, options, &keyfinder) raise JWT::DecodeError, 'Nil JSON web token' unless jwt @token = EncodedToken.new(jwt) @key = key @options = options @verify = verify @keyfinder = keyfinder end
Initializes a new Decode instance. @param jwt [String] the JWT to decode. @param key [String, Array<String>] the key(s) to use for verification. @param verify [Boolean] whether to verify the token's signature. @param options [Hash] additional options for decoding and verification. @param keyfinder [Proc] an optional key finder block to dynamically find the key for verification. @raise [JWT::DecodeError] if decoding or verification fails.
initialize
ruby
jwt/ruby-jwt
lib/jwt/decode.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/decode.rb
MIT
def decode_segments validate_segment_count! if @verify verify_algo set_key verify_signature Claims::DecodeVerifier.verify!(token.unverified_payload, @options) end [token.unverified_payload, token.header] end
Decodes the JWT token and verifies its segments if verification is enabled. @return [Array<Hash>] an array containing the decoded payload and header.
decode_segments
ruby
jwt/ruby-jwt
lib/jwt/decode.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/decode.rb
MIT
def initialize(options) @token = Token.new(payload: options[:payload], header: options[:headers]) @key = options[:key] @algorithm = options[:algorithm] end
Initializes a new Encode instance. @param options [Hash] the options for encoding the JWT token. @option options [Hash] :payload the payload of the JWT token. @option options [Hash] :headers the headers of the JWT token. @option options [String] :key the key used to sign the JWT token. @option options [String] :algorithm the algorithm used to sign the JWT token.
initialize
ruby
jwt/ruby-jwt
lib/jwt/encode.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/encode.rb
MIT
def segments @token.verify_claims!(:numeric) @token.sign!(algorithm: @algorithm, key: @key) @token.jwt end
Encodes the JWT token and returns its segments. @return [String] the encoded JWT token.
segments
ruby
jwt/ruby-jwt
lib/jwt/encode.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/encode.rb
MIT
def initialize(jwt) raise ArgumentError, 'Provided JWT must be a String' unless jwt.is_a?(String) @jwt = jwt @signature_verified = false @encoded_header, @encoded_payload, @encoded_signature = jwt.split('.') end
Initializes a new EncodedToken instance. @param jwt [String] the encoded JWT token. @raise [ArgumentError] if the provided JWT is not a String.
initialize
ruby
jwt/ruby-jwt
lib/jwt/encoded_token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/encoded_token.rb
MIT
def signature @signature ||= ::JWT::Base64.url_decode(encoded_signature || '') end
Returns the decoded signature of the JWT token. @return [String] the decoded signature.
signature
ruby
jwt/ruby-jwt
lib/jwt/encoded_token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/encoded_token.rb
MIT
def header @header ||= parse_and_decode(@encoded_header) end
Returns the decoded header of the JWT token. @return [Hash] the header.
header
ruby
jwt/ruby-jwt
lib/jwt/encoded_token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/encoded_token.rb
MIT
def payload raise JWT::DecodeError, 'Verify the token signature before accessing the payload' unless @signature_verified decoded_payload end
Returns the payload of the JWT token. Access requires the signature to have been verified. @return [Hash] the payload. @raise [JWT::DecodeError] if the signature has not been verified.
payload
ruby
jwt/ruby-jwt
lib/jwt/encoded_token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/encoded_token.rb
MIT
def signing_input [encoded_header, encoded_payload].join('.') end
Returns the signing input of the JWT token. @return [String] the signing input.
signing_input
ruby
jwt/ruby-jwt
lib/jwt/encoded_token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/encoded_token.rb
MIT
def verify!(signature:, claims: [:exp]) verify_signature!(**signature) claims.is_a?(Array) ? verify_claims!(*claims) : verify_claims!(claims) nil end
Verifies the token signature and claims. By default it verifies the 'exp' claim. @example encoded_token.verify!(signature: { algorithm: 'HS256', key: 'secret' }, claims: [:exp]) @param signature [Hash] the parameters for signature verification (see {#verify_signature!}). @param claims [Array<Symbol>, Hash] the claims to verify (see {#verify_claims!}). @return [nil] @raise [JWT::DecodeError] if the signature or claim verification fails.
verify!
ruby
jwt/ruby-jwt
lib/jwt/encoded_token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/encoded_token.rb
MIT
def verify_signature!(algorithm:, key: nil, key_finder: nil) raise ArgumentError, 'Provide either key or key_finder, not both or neither' if key.nil? == key_finder.nil? key ||= key_finder.call(self) return if valid_signature?(algorithm: algorithm, key: key) raise JWT::VerificationError, 'Signature verification failed' end
Verifies the signature of the JWT token. @param algorithm [String, Array<String>, Object, Array<Object>] the algorithm(s) to use for verification. @param key [String, Array<String>] the key(s) to use for verification. @param key_finder [#call] an object responding to `call` to find the key for verification. @return [nil] @raise [JWT::VerificationError] if the signature verification fails. @raise [ArgumentError] if neither key nor key_finder is provided, or if both are provided.
verify_signature!
ruby
jwt/ruby-jwt
lib/jwt/encoded_token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/encoded_token.rb
MIT
def valid_signature?(algorithm:, key:) valid = Array(JWA.resolve_and_sort(algorithms: algorithm, preferred_algorithm: header['alg'])).any? do |algo| Array(key).any? do |one_key| algo.verify(data: signing_input, signature: signature, verification_key: one_key) end end valid.tap { |verified| @signature_verified = verified } end
Checks if the signature of the JWT token is valid. @param algorithm [String, Array<String>, Object, Array<Object>] the algorithm(s) to use for verification. @param key [String, Array<String>] the key(s) to use for verification. @return [Boolean] true if the signature is valid, false otherwise.
valid_signature?
ruby
jwt/ruby-jwt
lib/jwt/encoded_token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/encoded_token.rb
MIT
def verify_claims!(*options) Claims::Verifier.verify!(ClaimsContext.new(self), *options) end
Verifies the claims of the token. @param options [Array<Symbol>, Hash] the claims to verify. @raise [JWT::DecodeError] if the claims are invalid.
verify_claims!
ruby
jwt/ruby-jwt
lib/jwt/encoded_token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/encoded_token.rb
MIT
def claim_errors(*options) Claims::Verifier.errors(ClaimsContext.new(self), *options) end
Returns the errors of the claims of the token. @param options [Array<Symbol>, Hash] the claims to verify. @return [Array<Symbol>] the errors of the claims.
claim_errors
ruby
jwt/ruby-jwt
lib/jwt/encoded_token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/encoded_token.rb
MIT
def initialize(payload:, header: {}) @header = header&.transform_keys(&:to_s) @payload = payload end
Initializes a new Token instance. @param header [Hash] the header of the JWT token. @param payload [Hash] the payload of the JWT token.
initialize
ruby
jwt/ruby-jwt
lib/jwt/token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/token.rb
MIT
def signature @signature ||= ::JWT::Base64.url_decode(encoded_signature || '') end
Returns the decoded signature of the JWT token. @return [String] the decoded signature of the JWT token.
signature
ruby
jwt/ruby-jwt
lib/jwt/token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/token.rb
MIT
def encoded_signature @encoded_signature ||= ::JWT::Base64.url_encode(signature) end
Returns the encoded signature of the JWT token. @return [String] the encoded signature of the JWT token.
encoded_signature
ruby
jwt/ruby-jwt
lib/jwt/token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/token.rb
MIT
def encoded_header @encoded_header ||= ::JWT::Base64.url_encode(JWT::JSON.generate(header)) end
Returns the encoded header of the JWT token. @return [String] the encoded header of the JWT token.
encoded_header
ruby
jwt/ruby-jwt
lib/jwt/token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/token.rb
MIT
def encoded_payload @encoded_payload ||= ::JWT::Base64.url_encode(JWT::JSON.generate(payload)) end
Returns the encoded payload of the JWT token. @return [String] the encoded payload of the JWT token.
encoded_payload
ruby
jwt/ruby-jwt
lib/jwt/token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/token.rb
MIT
def signing_input @signing_input ||= [encoded_header, encoded_payload].join('.') end
Returns the signing input of the JWT token. @return [String] the signing input of the JWT token.
signing_input
ruby
jwt/ruby-jwt
lib/jwt/token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/token.rb
MIT
def jwt @jwt ||= (@signature && [encoded_header, @detached_payload ? '' : encoded_payload, encoded_signature].join('.')) || raise(::JWT::EncodeError, 'Token is not signed') end
Returns the JWT token as a string. @return [String] the JWT token as a string. @raise [JWT::EncodeError] if the token is not signed or other encoding issues
jwt
ruby
jwt/ruby-jwt
lib/jwt/token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/token.rb
MIT
def detach_payload! @detached_payload = true nil end
Detaches the payload according to https://datatracker.ietf.org/doc/html/rfc7515#appendix-F
detach_payload!
ruby
jwt/ruby-jwt
lib/jwt/token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/token.rb
MIT
def sign!(algorithm:, key:) raise ::JWT::EncodeError, 'Token already signed' if @signature JWA.resolve(algorithm).tap do |algo| header.merge!(algo.header) { |_key, old, _new| old } @signature = algo.sign(data: signing_input, signing_key: key) end nil end
Signs the JWT token. @param algorithm [String, Object] the algorithm to use for signing. @param key [String] the key to use for signing. @return [void] @raise [JWT::EncodeError] if the token is already signed or other problems when signing
sign!
ruby
jwt/ruby-jwt
lib/jwt/token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/token.rb
MIT
def verify_claims!(*options) Claims::Verifier.verify!(self, *options) end
Verifies the claims of the token. @param options [Array<Symbol>, Hash] the claims to verify. @raise [JWT::DecodeError] if the claims are invalid.
verify_claims!
ruby
jwt/ruby-jwt
lib/jwt/token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/token.rb
MIT
def claim_errors(*options) Claims::Verifier.errors(self, *options) end
Returns the errors of the claims of the token. @param options [Array<Symbol>, Hash] the claims to verify. @return [Array<Symbol>] the errors of the claims.
claim_errors
ruby
jwt/ruby-jwt
lib/jwt/token.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/token.rb
MIT
def initialize(expected_audience:) @expected_audience = expected_audience end
Initializes a new Audience instance. @param expected_audience [String, Array<String>] the expected audience(s) for the JWT token.
initialize
ruby
jwt/ruby-jwt
lib/jwt/claims/audience.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/claims/audience.rb
MIT
def verify!(context:, **_args) aud = context.payload['aud'] raise JWT::InvalidAudError, "Invalid audience. Expected #{expected_audience}, received #{aud || '<none>'}" if ([*aud] & [*expected_audience]).empty? end
Verifies the audience claim ('aud') in the JWT token. @param context [Object] the context containing the JWT payload. @param _args [Hash] additional arguments (not used). @raise [JWT::InvalidAudError] if the audience claim is invalid. @return [nil]
verify!
ruby
jwt/ruby-jwt
lib/jwt/claims/audience.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/claims/audience.rb
MIT
def initialize(expected_crits:) @expected_crits = Array(expected_crits) end
Initializes a new Crit instance. @param expected_crits [String] the expected crit header values for the JWT token.
initialize
ruby
jwt/ruby-jwt
lib/jwt/claims/crit.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/claims/crit.rb
MIT
def verify!(context:, **_args) raise(JWT::InvalidCritError, 'Crit header missing') unless context.header['crit'] raise(JWT::InvalidCritError, 'Crit header should be an array') unless context.header['crit'].is_a?(Array) missing = (expected_crits - context.header['crit']) raise(JWT::InvalidCritError, "Crit header missing expected values: #{missing.join(', ')}") if missing.any? nil end
Verifies the critical claim ('crit') in the JWT token header. @param context [Object] the context containing the JWT payload and header. @param _args [Hash] additional arguments (not used). @raise [JWT::InvalidCritError] if the crit claim is invalid. @return [nil]
verify!
ruby
jwt/ruby-jwt
lib/jwt/claims/crit.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/claims/crit.rb
MIT
def initialize(leeway:) @leeway = leeway || 0 end
Initializes a new Expiration instance. @param leeway [Integer] the amount of leeway (in seconds) to allow when validating the expiration time. Default: 0.
initialize
ruby
jwt/ruby-jwt
lib/jwt/claims/expiration.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/claims/expiration.rb
MIT
def verify!(context:, **_args) return unless context.payload.is_a?(Hash) return unless context.payload.key?('exp') raise JWT::ExpiredSignature, 'Signature has expired' if context.payload['exp'].to_i <= (Time.now.to_i - leeway) end
Verifies the expiration claim ('exp') in the JWT token. @param context [Object] the context containing the JWT payload. @param _args [Hash] additional arguments (not used). @raise [JWT::ExpiredSignature] if the token has expired. @return [nil]
verify!
ruby
jwt/ruby-jwt
lib/jwt/claims/expiration.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/claims/expiration.rb
MIT
def verify!(context:, **_args) return unless context.payload.is_a?(Hash) return unless context.payload.key?('iat') iat = context.payload['iat'] raise(JWT::InvalidIatError, 'Invalid iat') if !iat.is_a?(::Numeric) || iat.to_f > Time.now.to_f end
Verifies the issued at claim ('iat') in the JWT token. @param context [Object] the context containing the JWT payload. @param _args [Hash] additional arguments (not used). @raise [JWT::InvalidIatError] if the issued at claim is invalid. @return [nil]
verify!
ruby
jwt/ruby-jwt
lib/jwt/claims/issued_at.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/claims/issued_at.rb
MIT
def initialize(issuers:) @issuers = Array(issuers).map { |item| item.is_a?(Symbol) ? item.to_s : item } end
Initializes a new Issuer instance. @param issuers [String, Symbol, Array<String, Symbol>] the expected issuer(s) for the JWT token.
initialize
ruby
jwt/ruby-jwt
lib/jwt/claims/issuer.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/claims/issuer.rb
MIT
def verify!(context:, **_args) case (iss = context.payload['iss']) when *issuers nil else raise JWT::InvalidIssuerError, "Invalid issuer. Expected #{issuers}, received #{iss || '<none>'}" end end
Verifies the issuer claim ('iss') in the JWT token. @param context [Object] the context containing the JWT payload. @param _args [Hash] additional arguments (not used). @raise [JWT::InvalidIssuerError] if the issuer claim is invalid. @return [nil]
verify!
ruby
jwt/ruby-jwt
lib/jwt/claims/issuer.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/claims/issuer.rb
MIT
def initialize(validator:) @validator = validator end
Initializes a new JwtId instance. @param validator [#call] an object responding to `call` to validate the JWT ID.
initialize
ruby
jwt/ruby-jwt
lib/jwt/claims/jwt_id.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/claims/jwt_id.rb
MIT
def verify!(context:, **_args) jti = context.payload['jti'] if validator.respond_to?(:call) verified = validator.arity == 2 ? validator.call(jti, context.payload) : validator.call(jti) raise(JWT::InvalidJtiError, 'Invalid jti') unless verified elsif jti.to_s.strip.empty? raise(JWT::InvalidJtiError, 'Missing jti') end end
Verifies the JWT ID claim ('jti') in the JWT token. @param context [Object] the context containing the JWT payload. @param _args [Hash] additional arguments (not used). @raise [JWT::InvalidJtiError] if the JWT ID claim is invalid or missing. @return [nil]
verify!
ruby
jwt/ruby-jwt
lib/jwt/claims/jwt_id.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/claims/jwt_id.rb
MIT
def initialize(leeway:) @leeway = leeway || 0 end
Initializes a new NotBefore instance. @param leeway [Integer] the amount of leeway (in seconds) to allow when validating the 'nbf' claim. Defaults to 0.
initialize
ruby
jwt/ruby-jwt
lib/jwt/claims/not_before.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/claims/not_before.rb
MIT
def verify!(context:, **_args) return unless context.payload.is_a?(Hash) return unless context.payload.key?('nbf') raise JWT::ImmatureSignature, 'Signature nbf has not been reached' if context.payload['nbf'].to_i > (Time.now.to_i + leeway) end
Verifies the 'nbf' (Not Before) claim in the JWT token. @param context [Object] the context containing the JWT payload. @param _args [Hash] additional arguments (not used). @raise [JWT::ImmatureSignature] if the 'nbf' claim has not been reached. @return [nil]
verify!
ruby
jwt/ruby-jwt
lib/jwt/claims/not_before.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/claims/not_before.rb
MIT
def initialize(required_claims:) @required_claims = required_claims end
Initializes a new Required instance. @param required_claims [Array<String>] the list of required claims.
initialize
ruby
jwt/ruby-jwt
lib/jwt/claims/required.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/claims/required.rb
MIT
def verify!(context:, **_args) required_claims.each do |required_claim| next if context.payload.is_a?(Hash) && context.payload.key?(required_claim) raise JWT::MissingRequiredClaim, "Missing required claim #{required_claim}" end end
Verifies that all required claims are present in the JWT payload. @param context [Object] the context containing the JWT payload. @param _args [Hash] additional arguments (not used). @raise [JWT::MissingRequiredClaim] if any required claim is missing. @return [nil]
verify!
ruby
jwt/ruby-jwt
lib/jwt/claims/required.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/claims/required.rb
MIT
def initialize(expected_subject:) @expected_subject = expected_subject.to_s end
Initializes a new Subject instance. @param expected_subject [String] the expected subject for the JWT token.
initialize
ruby
jwt/ruby-jwt
lib/jwt/claims/subject.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/claims/subject.rb
MIT
def verify!(context:, **_args) sub = context.payload['sub'] raise(JWT::InvalidSubError, "Invalid subject. Expected #{expected_subject}, received #{sub || '<none>'}") unless sub.to_s == expected_subject end
Verifies the subject claim ('sub') in the JWT token. @param context [Object] the context containing the JWT payload. @param _args [Hash] additional arguments (not used). @raise [JWT::InvalidSubError] if the subject claim is invalid. @return [nil]
verify!
ruby
jwt/ruby-jwt
lib/jwt/claims/subject.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/claims/subject.rb
MIT
def reset! @decode = DecodeConfiguration.new @jwk = JwkConfiguration.new self.deprecation_warnings = :once end
Resets the configuration to default values. @return [void]
reset!
ruby
jwt/ruby-jwt
lib/jwt/configuration/container.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/configuration/container.rb
MIT
def initialize @verify_expiration = true @verify_not_before = true @verify_iss = false @verify_iat = false @verify_jti = false @verify_aud = false @verify_sub = false @leeway = 0 @algorithms = ['HS256'] @required_claims = [] end
Initializes a new DecodeConfiguration instance with default settings.
initialize
ruby
jwt/ruby-jwt
lib/jwt/configuration/decode_configuration.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/configuration/decode_configuration.rb
MIT
def secure_compare(a, b) a.bytesize == b.bytesize && fixed_length_secure_compare(a, b) end
Secure string comparison for strings of variable length. While a timing attack would not be able to discern the content of a secret compared via secure_compare, it is possible to determine the secret length. This should be considered when using secure_compare to compare weak, short secrets to user input.
secure_compare
ruby
jwt/ruby-jwt
lib/jwt/jwa/hmac.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/jwa/hmac.rb
MIT
def export(options = {}) exported = parameters.clone exported.reject! { |k, _| HMAC_PRIVATE_KEY_ELEMENTS.include? k } unless private? && options[:include_private] == true exported end
See https://tools.ietf.org/html/rfc7517#appendix-A.3
export
ruby
jwt/ruby-jwt
lib/jwt/jwk/hmac.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/jwk/hmac.rb
MIT
def initialize(options) @allow_nil_kid = options[:allow_nil_kid] jwks_or_loader = options[:jwks] @jwks_loader = if jwks_or_loader.respond_to?(:call) jwks_or_loader else ->(_options) { jwks_or_loader } end end
Initializes a new KeyFinder instance. @param [Hash] options the options to create a KeyFinder with @option options [Proc, JWT::JWK::Set] :jwks the jwks or a loader proc @option options [Boolean] :allow_nil_kid whether to allow nil kid
initialize
ruby
jwt/ruby-jwt
lib/jwt/jwk/key_finder.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/jwk/key_finder.rb
MIT
def key_for(kid) raise ::JWT::DecodeError, 'No key id (kid) found from token headers' unless kid || @allow_nil_kid raise ::JWT::DecodeError, 'Invalid type for kid header parameter' unless kid.nil? || kid.is_a?(String) jwk = resolve_key(kid) raise ::JWT::DecodeError, 'No keys found in jwks' unless @jwks.any? raise ::JWT::DecodeError, "Could not find public key for kid #{kid}" unless jwk jwk.verify_key end
Returns the verification key for the given kid @param [String] kid the key id
key_for
ruby
jwt/ruby-jwt
lib/jwt/jwk/key_finder.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/jwk/key_finder.rb
MIT
def create_rsa_key_using_accessors(rsa_parameters) # rubocop:disable Metrics/AbcSize validate_rsa_parameters!(rsa_parameters) OpenSSL::PKey::RSA.new.tap do |rsa_key| rsa_key.n = rsa_parameters[:n] rsa_key.e = rsa_parameters[:e] rsa_key.d = rsa_parameters[:d] if rsa_parameters[:d] rsa_key.p = rsa_parameters[:p] if rsa_parameters[:p] rsa_key.q = rsa_parameters[:q] if rsa_parameters[:q] rsa_key.dmp1 = rsa_parameters[:dp] if rsa_parameters[:dp] rsa_key.dmq1 = rsa_parameters[:dq] if rsa_parameters[:dq] rsa_key.iqmp = rsa_parameters[:qi] if rsa_parameters[:qi] end end
:nocov: Before openssl 2.0, we need to use the accessors to set the key
create_rsa_key_using_accessors
ruby
jwt/ruby-jwt
lib/jwt/jwk/rsa.rb
https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/jwk/rsa.rb
MIT
def javascript_importmap_tags(entry_point = "application", importmap: Rails.application.importmap) safe_join [ javascript_inline_importmap_tag(importmap.to_json(resolver: self)), javascript_importmap_module_preload_tags(importmap, entry_point:), javascript_import_module_tag(entry_point) ], "\n" end
Setup all script tags needed to use an importmap-powered entrypoint (which defaults to application.js)
javascript_importmap_tags
ruby
rails/importmap-rails
app/helpers/importmap/importmap_tags_helper.rb
https://github.com/rails/importmap-rails/blob/master/app/helpers/importmap/importmap_tags_helper.rb
MIT
def javascript_inline_importmap_tag(importmap_json = Rails.application.importmap.to_json(resolver: self)) tag.script importmap_json.html_safe, type: "importmap", "data-turbo-track": "reload", nonce: request&.content_security_policy_nonce end
Generate an inline importmap tag using the passed `importmap_json` JSON string. By default, `Rails.application.importmap.to_json(resolver: self)` is used.
javascript_inline_importmap_tag
ruby
rails/importmap-rails
app/helpers/importmap/importmap_tags_helper.rb
https://github.com/rails/importmap-rails/blob/master/app/helpers/importmap/importmap_tags_helper.rb
MIT
def javascript_import_module_tag(*module_names) imports = Array(module_names).collect { |m| %(import "#{m}") }.join("\n") tag.script imports.html_safe, type: "module", nonce: request&.content_security_policy_nonce end
Import a named JavaScript module(s) using a script-module tag.
javascript_import_module_tag
ruby
rails/importmap-rails
app/helpers/importmap/importmap_tags_helper.rb
https://github.com/rails/importmap-rails/blob/master/app/helpers/importmap/importmap_tags_helper.rb
MIT
def javascript_importmap_module_preload_tags(importmap = Rails.application.importmap, entry_point: "application") javascript_module_preload_tag(*importmap.preloaded_module_paths(resolver: self, entry_point:, cache_key: entry_point)) end
Link tags for preloading all modules marked as preload: true in the `importmap` (defaults to Rails.application.importmap), such that they'll be fetched in advance by browsers supporting this link type (https://caniuse.com/?search=modulepreload).
javascript_importmap_module_preload_tags
ruby
rails/importmap-rails
app/helpers/importmap/importmap_tags_helper.rb
https://github.com/rails/importmap-rails/blob/master/app/helpers/importmap/importmap_tags_helper.rb
MIT
def javascript_module_preload_tag(*paths) safe_join(Array(paths).collect { |path| tag.link rel: "modulepreload", href: path, nonce: request&.content_security_policy_nonce }, "\n") end
Link tag(s) for preloading the JavaScript module residing in `*paths`. Will return one link tag per path element.
javascript_module_preload_tag
ruby
rails/importmap-rails
app/helpers/importmap/importmap_tags_helper.rb
https://github.com/rails/importmap-rails/blob/master/app/helpers/importmap/importmap_tags_helper.rb
MIT
def preloaded_module_paths(resolver:, entry_point: "application", cache_key: :preloaded_module_paths) cache_as(cache_key) do resolve_asset_paths(expanded_preloading_packages_and_directories(entry_point:), resolver:).values end end
Returns an array of all the resolved module paths of the pinned packages. The `resolver` must respond to `path_to_asset`, such as `ActionController::Base.helpers` or `ApplicationController.helpers`. You'll want to use the resolver that has been configured for the `asset_host` you want these resolved paths to use. In case you need to resolve for different asset hosts, you can pass in a custom `cache_key` to vary the cache used by this method for the different cases.
preloaded_module_paths
ruby
rails/importmap-rails
lib/importmap/map.rb
https://github.com/rails/importmap-rails/blob/master/lib/importmap/map.rb
MIT
def to_json(resolver:, cache_key: :json) cache_as(cache_key) do JSON.pretty_generate({ "imports" => resolve_asset_paths(expanded_packages_and_directories, resolver: resolver) }) end end
Returns a JSON hash (as a string) of all the resolved module paths of the pinned packages in the import map format. The `resolver` must respond to `path_to_asset`, such as `ActionController::Base.helpers` or `ApplicationController.helpers`. You'll want to use the resolver that has been configured for the `asset_host` you want these resolved paths to use. In case you need to resolve for different asset hosts, you can pass in a custom `cache_key` to vary the cache used by this method for the different cases.
to_json
ruby
rails/importmap-rails
lib/importmap/map.rb
https://github.com/rails/importmap-rails/blob/master/lib/importmap/map.rb
MIT
def digest(resolver:) Digest::SHA1.hexdigest(to_json(resolver: resolver).to_s) end
Returns a SHA1 digest of the import map json that can be used as a part of a page etag to ensure that a html cache is invalidated when the import map is changed. Example: class ApplicationController < ActionController::Base etag { Rails.application.importmap.digest(resolver: helpers) if request.format&.html? } end
digest
ruby
rails/importmap-rails
lib/importmap/map.rb
https://github.com/rails/importmap-rails/blob/master/lib/importmap/map.rb
MIT
def cache_sweeper(watches: nil) if watches @cache_sweeper = Rails.application.config.file_watcher.new([], Array(watches).collect { |dir| [ dir.to_s, "js"] }.to_h) do clear_cache end else @cache_sweeper end end
Returns an instance of ActiveSupport::EventedFileUpdateChecker configured to clear the cache of the map when the directories passed on initialization via `watches:` have changes. This is used in development and test to ensure the map caches are reset when javascript files are changed.
cache_sweeper
ruby
rails/importmap-rails
lib/importmap/map.rb
https://github.com/rails/importmap-rails/blob/master/lib/importmap/map.rb
MIT
def parse(string) @base = {} toks = string.split("/") return parse_base(toks) end
It parses a string and it says if it's a good CVSS vector or not.
parse
ruby
thesp0nge/dawnscanner
lib/cvss/parser.rb
https://github.com/thesp0nge/dawnscanner/blob/master/lib/cvss/parser.rb
MIT
def output_dir @output_dir_name = File.join(Dir.home, 'dawnscanner', 'results', File.basename(@target), Time.now.strftime('%Y%m%d')) if Dir.exist?(@output_dir_name) i=1 while (Dir.exist?(@output_dir_name)) do @output_dir_name = File.join(Dir.home, 'dawnscanner', 'results', File.basename(@target), "#{Time.now.strftime('%Y%m%d')}_#{i}") i+=1 end end @output_dir_name end
####################################################################### # Output stuff - START ####################################################################### Creates the directory name where dawnscanner results will be saved Examples engine.create_output_dir # => /Users/thesp0nge/dawnscanner/results/railsgoat/20151123 # => /Users/thesp0nge/dawnscanner/results/railsgoat/20151123_1 (if previous directory name exists)
output_dir
ruby
thesp0nge/dawnscanner
lib/dawn/engine.rb
https://github.com/thesp0nge/dawnscanner/blob/master/lib/dawn/engine.rb
MIT
def apply(name) # FIXME.20140325 # Now if no checks are loaded because knowledge base was not previously called, apply and apply_all proudly refuse to run. # Reason is simple, load_knowledge_base now needs enabled check array # and I don't want to pollute engine API to propagate this value. It's # a param to load_knowledge_base and then bin/dawn calls it # accordingly. # load_knowledge_base if @checks.nil? if @checks.nil? $logger.err "you must load knowledge base before trying to apply security checks" return false end return false if @checks.empty? @checks.each do |check| _do_apply(check) if check.name == name end false end
####################################################################### # Output stuff - END ####################################################################### # Security stuff applies here Public it applies a single security check given by its name name - the security check to be applied Examples engine.apply("CVE-2013-1800") # => boolean Returns a true value if the security check was successfully applied or false otherwise
apply
ruby
thesp0nge/dawnscanner
lib/dawn/engine.rb
https://github.com/thesp0nge/dawnscanner/blob/master/lib/dawn/engine.rb
MIT
def default_path path_list=[File.join(Dir.home, "dawnscanner", "kb"), "/usr/share/dawnscanner/kb", "/usr/local/share/dawnscanner/kb"] path_list.each do |p| if Dir.exist?(p) @path = p return @path end end @path = "" return @path end
Starting from version 2.3.0 the knowledge base will be searched in different locations and it will be used the first found. 1. $HOME/dawnscanner/kb 2. /usr/share/dawnscanner/kb 3. /usr/local/share/dawnscanner/kb
default_path
ruby
thesp0nge/dawnscanner
lib/dawn/knowledge_base.rb
https://github.com/thesp0nge/dawnscanner/blob/master/lib/dawn/knowledge_base.rb
MIT
def find_issues_by_gem(string = "") issues = [] @security_checks.each do |check| if check.kind == Dawn::KnowledgeBase::DEPENDENCY_CHECK or check.kind == Dawn::KnowledgeBase::UNSAFE_DEPENDENCY_CHECK debug_me "applying check #{check.name}" name = string.split(':')[0] version = string.split(':')[1] check.please_ignore_dep_version = true if version.nil? check.dependencies = [{:name=>name, :version=>version}] issues << check if check.vuln? end end debug_me "#{issues}" return issues end
Find all security issues affecting the gem passed as argument. The gem parameter can contains also the version number, separated by a ':' == Parameters: string:: A string containing the gem name, and eventually the version, to search for vulnerabilities. e.g. $ dawn kb list sinatra => returns all bulletins affecting sinatra gem $ dawn kb list sinatra 2.0.0 => return all bulletins affecting sinatra gem version 2.0.0 == Returns: An array with all the vulnerabilities affecting the gem (or the particular gem version if provided).
find_issues_by_gem
ruby
thesp0nge/dawnscanner
lib/dawn/knowledge_base.rb
https://github.com/thesp0nge/dawnscanner/blob/master/lib/dawn/knowledge_base.rb
MIT
def load(lint=false) good =0 invalid =0 unless @security_checks.nil? debug_me("KB was previously loaded") return @security_checks end @security_checks = [] # $path = File.join(Dir.pwd, "db") unless __valid? @error = "An invalid library it has been found. Please use --recovery flag to force fresh install from dawnscanner.org" return [] end unless __load? @error = "The library must be consumed with dawnscanner up to v#{@descriptor[:kb][:api]}. You are using dawnscanner v#{Dawn::VERSION}" return [] end @enabled_checks.each do |d| dir = File.join(@path, d.to_s) # Please note that if we enter in this branch, it means someone # tampered the KB between the previous __valid? check and this point. # Of course this is a very rare situation, but we must handle it. unless Dir.exist?(dir) $logger.warn "Missing check directory #{dir}" else Dir.glob(dir+"/**/*.yml").each do |f| begin data = YAML.load_file(f, permitted_classes: [Dawn::Kb::UnsafeDependencyCheck, Dawn::Kb::BasicCheck, Dawn::Kb::ComboCheck, Dawn::Kb::DependencyCheck, Dawn::Kb::DeprecationCheck, Dawn::Kb::OperatingSystemCheck, Dawn::Kb::PatternMatchCheck, Dawn::Kb::RubygemCheck, Dawn::Kb::RubyVersionCheck, Dawn::Kb::VersionCheck, Date, Symbol]) @security_checks << data good+=1 $logger.info("#{File.basename(f)} loaded") if lint rescue Exception => e $logger.error(e.message) invalid+=1 end end end if lint $logger.info("#{invalid} invalid checks out of #{good+invalid}") end end debug_me "#{@security_checks.count}" return @security_checks end
Load security checks from db/ folder. Returns an array of security checks, matching the mvc to be reviewed and the enabled check list or an empty array if an error occured.
load
ruby
thesp0nge/dawnscanner
lib/dawn/knowledge_base.rb
https://github.com/thesp0nge/dawnscanner/blob/master/lib/dawn/knowledge_base.rb
MIT
def __packed? FILES.each do |fn| return true if fn.end_with? 'tar.gz' and File.exist?(File.join(@path, fn)) end return false end
Check if the local KB is packet or not. Returns true if at least one KB tarball file it has been found in the local DB path
__packed?
ruby
thesp0nge/dawnscanner
lib/dawn/knowledge_base.rb
https://github.com/thesp0nge/dawnscanner/blob/master/lib/dawn/knowledge_base.rb
MIT
def detect_appname(target) return "app.rb" if File.exist?(File.join(self.target, "app.rb")) return "application.rb" if File.exist?(File.join(self.target, "application.rb")) file_array = Dir.glob(File.join("#{target}", "*.rb")) return file_array[0] if ! file_array.nil? and file_array.count == 1 return "" # gracefully failure end
TODO: appname should be hopefully autodetect from config.ru
detect_appname
ruby
thesp0nge/dawnscanner
lib/dawn/sinatra.rb
https://github.com/thesp0nge/dawnscanner/blob/master/lib/dawn/sinatra.rb
MIT
def lint ret = [] ret << :cve if self.cve.nil? ret << :osvdb if @osvdb.nil? ret << :cvss if self.cvss.nil? || self.cvss.empty? || self.cvss == "not assigned" ret << :severity if self.severity == "unknown" ret << :priority if self.priority == "unknown" ret << :title if self.title.nil? ret end
Performs a self check against some core values from being not nil @return an Array with attributes with a nil value
lint
ruby
thesp0nge/dawnscanner
lib/dawn/kb/basic_check.rb
https://github.com/thesp0nge/dawnscanner/blob/master/lib/dawn/kb/basic_check.rb
MIT
def initialize(options) super(options) @save_minor ||= options[:save_minor] @save_major ||= options[:save_major] warn "This class is deprecated. Please use UnsafeDependencyCheck instead" end
@deprecated Please use UnsafeDependencyCheck instead. This class is no longer supperted and it will be removed really soon.
initialize
ruby
thesp0nge/dawnscanner
lib/dawn/kb/dependency_check.rb
https://github.com/thesp0nge/dawnscanner/blob/master/lib/dawn/kb/dependency_check.rb
MIT
def is_higher?(a, b) aa = version_string_to_array(a) ba = version_string_to_array(b) ver = false beta = false rc = false same = false # Version arrays are just major.minor version. Let's assume # patchlevel is 0 for sake of comparison. aa[:version] << 0 if aa[:version].count == 2 ba[:version] << 0 if ba[:version].count == 2 # Handling a = '1.2.3.4' and b = '1.2.3' ba[:version] << 0 if aa[:version].count == 4 and ba[:version].count == 3 ver = true if aa[:version][0] > ba[:version][0] ver = true if aa[:version][0] == ba[:version][0] && aa[:version][1] > ba[:version][1] ver = true if aa[:version].count == 3 && ba[:version].count == 3 && aa[:version][0] == ba[:version][0] && aa[:version][1] == ba[:version][1] && aa[:version][2] > ba[:version][2] ver = true if aa[:version].count == 4 && ba[:version].count == 4 && aa[:version][0] == ba[:version][0] && aa[:version][1] == ba[:version][1] && aa[:version][2] == ba[:version][2] && aa[:version][3] > ba[:version][3] ver = true if aa[:version].count == 4 && ba[:version].count == 4 && aa[:version][0] == ba[:version][0] && aa[:version][1] == ba[:version][1] && aa[:version][2] > ba[:version][2] same = is_same_version?(aa[:version], ba[:version]) beta = true if aa[:beta] >= ba[:beta] rc = true if aa[:rc] >= ba[:rc] ret = false ret = ver && beta && rc unless same ret = beta && rc if same debug_verbosely("is_higher? a=#{a}, b=#{b} VER=#{ver} - BETA=#{beta} - RC=#{rc} - SAME=#{same} - a>b? = (#{ret})") return ret end
Public: tells if a version is higher than another e.g. is_higher?('2.3.2', '2.4.2') => true is_higher?('2.3.2', '2.3.2') => true
is_higher?
ruby
thesp0nge/dawnscanner
lib/dawn/kb/version_check.rb
https://github.com/thesp0nge/dawnscanner/blob/master/lib/dawn/kb/version_check.rb
MIT
def is_there_an_higher_major_version? dva = version_string_to_array(@detected)[:version] @safe.sort.each do |s| sva = version_string_to_array(s)[:version] debug_verbosely "is_there_an_higher_major_version? DVA=#{dva} - SVA=#{sva}" return debug_me_and_return_true("is_there_an_higher_major_version? is returning true for #{@detected}") if dva[0] < sva[0] end return debug_me_and_return_false("is_there_an_higher_major_version? is returning false") end
checks in the array if there is another string with higher major version
is_there_an_higher_major_version?
ruby
thesp0nge/dawnscanner
lib/dawn/kb/version_check.rb
https://github.com/thesp0nge/dawnscanner/blob/master/lib/dawn/kb/version_check.rb
MIT
def is_there_an_higher_minor_version? dva = version_string_to_array(@detected)[:version] @safe.sort.each do |s| sva = version_string_to_array(s)[:version] return true if dva[0] == sva[0] && dva[1] < sva[1] end return false end
checks in the array if there is another string with higher minor version but the same major as the parameter element)
is_there_an_higher_minor_version?
ruby
thesp0nge/dawnscanner
lib/dawn/kb/version_check.rb
https://github.com/thesp0nge/dawnscanner/blob/master/lib/dawn/kb/version_check.rb
MIT
def save_minor_fix return false unless @save_minor hm = is_there_an_higher_minor_version? # This is the save minor version workaround. # fixes is something like ['2.2.2', '3.1.1', '3.2.2'] # target is '3.1.1' and save_minor_fixes is true # I don't want that check for 3.2.2 marks this as vulnerable, so I will save it dva = version_string_to_array(@detected)[:version] @safe.sort.each do |s| sva = version_string_to_array(s)[:version] sM = is_same_major?(sva, dva) sm = is_same_minor?(sva, dva) debug_verbosely("save_minor_fix: SVA=#{sva};DVA=#{dva};SAME_MAJOR? = #{sM}; SAME_MINOR?=#{sm}; ( dva[2] >= sva[2] )=#{(dva[2] >= sva[2])}") debug_verbosely("save_minor_fix: is_there_higher_minor_version? = #{hm}") return true if sM and sm and dva[2] >= sva[2] && hm return true if sM and hm end return false end
# This functions handles an hack to save a detected version even if a safe version with an higher minor version number has been found. This is mostly used in rails where there are different versions and if a 3.2.12 is safe it should not marked as vulnerable just because you can either use 3.3.x that is a different branch. It returns true when the detected version must be saved, false otherwise.
save_minor_fix
ruby
thesp0nge/dawnscanner
lib/dawn/kb/version_check.rb
https://github.com/thesp0nge/dawnscanner/blob/master/lib/dawn/kb/version_check.rb
MIT
def is_same_major?(array_a, array_b) return false if ! is_good_parameter?(array_a) || ! is_good_parameter?(array_b) return (array_a[0] == array_b[0]) end
# It checks if the first digit of a version array is the same e.g. has_same_major?([2,3,3], [1,2,2]) #=> false has_same_major?([2,3,3], [2,2,2]) #=> true
is_same_major?
ruby
thesp0nge/dawnscanner
lib/dawn/kb/version_check.rb
https://github.com/thesp0nge/dawnscanner/blob/master/lib/dawn/kb/version_check.rb
MIT
def version_string_to_array(string) # I can't use this nice onliner... stays here until I finish writing new code. # return string.split(".").map! { |n| (n=='x')? n : n.to_i } ver = [] beta = -1 rc = -1 pre = -1 string.split(".").each do |x| ver << x.to_i unless x == 'x' || x.start_with?('beta') || x.start_with?('rc') || x.start_with?('pre') ver << x if x == 'x' beta = x.split("beta")[1].to_i if x.class == String && x.start_with?('beta') && beta == -1 rc = x.split("rc")[1].to_i if x.class == String && x.start_with?('rc') && rc == -1 pre = x.split("pre")[1].to_i if x.class == String && x.start_with?('pre') && pre == -1 end {:version=>ver, :beta=>beta, :rc=>rc, :pre=>pre} end
# It takes a string representing a version and it splits it in an Hash. e.g. version_string_to_array("3.2.3") #=> {:version=>[3,2,3], :beta=>0, :rc=>0} version_string_to_array("3.2.2.beta1") #=> {:version=>[3,2,2], :beta=>1, :rc=>0}
version_string_to_array
ruby
thesp0nge/dawnscanner
lib/dawn/kb/version_check.rb
https://github.com/thesp0nge/dawnscanner/blob/master/lib/dawn/kb/version_check.rb
MIT
def call(hunk, &block) case [hunk, attributes] in [{ orig_path: path, final_signature: { time: created_at } }, { after: }] unless created_at > after say("File %s ignored due to [created > after] (%p > %p)", path, created_at, after) in [{ orig_path: path, final_signature: { time: created_at } }, { before: }] unless created_at < before say("File %s ignored due to [created < before] (%p < %p)", path, created_at, before) in [{ orig_path: path}, { exclude: excluded }] if excluded.any? { File.fnmatch?(_1, path, OPT) } say("File %s excluded by [exclude] (%p)", path, excluded) in [{ orig_path: path }, { include: included }] unless included.any? { File.fnmatch?(_1, path, OPT) } say("File %s excluded by [include] (%p)", path, included) in [{ orig_path: path }, { extensions: }] unless extensions.any? { File.extname(path) == _1 } say("File %s excluded by [extensions] (%p)", path, extensions) in [{final_signature: { name:, email:}, final_commit_id: oid, lines_in_hunk: lines, orig_path: path}, Hash] block[lines, path, oid, name, email] end end
Invokes block if hunk is valid @param hunk [Hash] @yieldparam lines [Integer] @yieldparam orig_path [Pathname] @yieldparam oid [String] @yieldparam name [String] @yieldparam email [String] @return [void]
call
ruby
oleander/git-fame-rb
lib/git_fame/filter.rb
https://github.com/oleander/git-fame-rb/blob/master/lib/git_fame/filter.rb
MIT
def truncate(text, options = {}) return unless text.present? return super unless options.delete(:preserve_html_tags) == true # ensure preserve_html_tags doesn't pass through max_length = options[:length] || 30 omission = options[:omission] || "..." return truncate_html(text, :length => max_length, :word_boundary => true, :omission => omission) end
Like the Rails _truncate_ helper but doesn't break HTML tags, entities, and words. <script> tags pass through and are not counted in the total. the omission specified _does_ count toward the total length count. use :link => link_to('more', post_path), or something to that effect
truncate
ruby
refinery/refinerycms
core/app/helpers/refinery/html_truncation_helper.rb
https://github.com/refinery/refinerycms/blob/master/core/app/helpers/refinery/html_truncation_helper.rb
MIT
def content_fu(content, thumbnail) content.gsub(%r{<img.+?src=['"](/system/images/.+?)/.+?/>}) do |img| begin sha = img.match(%r{/system/images/(.+?)/})[1] job = Dragonfly::Job.deserialize sha, Dragonfly.app(:refinery_images) image_fu Image.where(:image_uid => job.uid).first, thumbnail rescue Dragonfly::Serializer::BadString img end end end
replace all system images with a thumbnail version of them (handy for all images inside a page part) for example, <%= content_fu(@page.content_for(:body), '96x96#c') %> converts all /system/images to a 96x96 cropped thumbnail
content_fu
ruby
refinery/refinerycms
core/app/helpers/refinery/image_helper.rb
https://github.com/refinery/refinerycms/blob/master/core/app/helpers/refinery/image_helper.rb
MIT
def image_fu(image, geometry = nil, options = {}) return nil if image.blank? thumbnail_args = options.slice(:strip) thumbnail_args[:geometry] = geometry if geometry image_tag_args = (image.thumbnail_dimensions(geometry) rescue {}) image_tag_args[:alt] = image.respond_to?(:title) ? image.title : image.image_name image_tag(image.thumbnail(thumbnail_args).url, image_tag_args.merge(options)) end
image_fu is a helper for inserting an image that has been uploaded into a template. Say for example that we had a @model.image (@model having a belongs_to :image relationship) and we wanted to display a thumbnail cropped to 200x200 then we can use image_fu like this: <%= image_fu @model.image, '200x200' %> or with no thumbnail: <%= image_fu @model.image %>
image_fu
ruby
refinery/refinerycms
core/app/helpers/refinery/image_helper.rb
https://github.com/refinery/refinerycms/blob/master/core/app/helpers/refinery/image_helper.rb
MIT
def browser_title(yield_title = nil) [ yield_title, @meta.browser_title.presence || @meta.path, Refinery::Core.site_name ].reject(&:blank?).join(" - ") end
This is used to display the title of the current object (normally a page) in the browser's titlebar.
browser_title
ruby
refinery/refinerycms
core/app/helpers/refinery/meta_helper.rb
https://github.com/refinery/refinerycms/blob/master/core/app/helpers/refinery/meta_helper.rb
MIT
def page_title(options = {}) object = options.fetch(:object, @meta) options.delete(:object) options = Refinery::Pages.page_title.merge(options) title = [] objects = (options[:chain_page_title] and object.respond_to?(:ancestors)) ? [object.ancestors, object] : [object] objects.flatten.compact.each do |obj| obj_title = obj.title if obj.title # Only link when the object responds to a url method. if options[:link] && obj.respond_to?(:url) title << link_to(obj_title, obj.url) else title << obj_title end end final_title = title.pop if (options[:page_title][:wrap_if_not_chained] and title.empty?) and options[:page_title][:tag].present? css = " class='#{options[:page_title][:class]}'" if options[:page_title][:class].present? final_title = "<#{options[:page_title][:tag]}#{css}>#{final_title}</#{options[:page_title][:tag]}>" end if title.empty? final_title.to_s.html_safe else tag = "<#{options[:ancestors][:tag]} class='#{options[:ancestors][:class]}'>" tag << title.join(options[:ancestors][:separator]) tag << options[:ancestors][:separator] tag << "</#{options[:ancestors][:tag]}>#{final_title}" tag.html_safe end end
you can override the object used for the title by supplying options[:object]
page_title
ruby
refinery/refinerycms
core/app/helpers/refinery/meta_helper.rb
https://github.com/refinery/refinerycms/blob/master/core/app/helpers/refinery/meta_helper.rb
MIT